package cn.player.media.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import cn.player.R;
import cntv.player.core.CBoxP2P;
import cntv.player.core.CBoxP2P.OnP2PBufferListener;
import cntv.player.core.CBoxP2P.OnP2PInitListener;
import cntv.player.core.CBoxStaticParam;
import cntv.player.core.util.AnimController;
import cntv.player.core.util.AnimController.AnimCallback;
import cntv.player.core.util.LogUtil;
import cntv.player.core.util.SprefUtils;
import cntv.player.core.util.StringUtil;
import cntv.player.core.util.ToastUtil;
import cntv.player.core.util.Utils;
import cntv.player.engine.Const;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnCompletionListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnErrorListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnPreparedListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnSurfaceListener;
import tv.danmaku.ijk.media.player.widget.BaseMediaController.OnVideoPlayListener;
import cntv.player.media.widget.KooVideoView;
import cn.player.media.PlayerConfig;
import cn.player.media.adapter.PlayModeAdaper;
import cn.player.media.entity.AdInfo;
import cn.player.media.entity.LiveEpg;
import cn.player.media.entity.LivePolicy;
import cn.player.media.entity.PlayMode;
import cn.player.media.entity.VdnLiveInfo;
import cn.player.media.entity.VideoInfo;
import cn.player.media.timeshift.RulerView;
import cn.player.media.timeshift.TimeShiftEPG;
import cn.player.media.timeshift.TimeShiftParams;
import cn.player.media.util.DateUtil;
import cn.player.media.util.DialogUtil;
import cn.player.media.util.ParseUtil;
import cn.player.media.view.CustomerMediaController;
import cn.player.media.view.MyHorizontalScrollView;
import cn.player.media.view.VerticalSeekBar;
import tv.danmaku.ijk.media.player.widget.IjkVideoView;

public class MediaPlayFragment extends BaseFragment {

    private static final String TAG = "zl";
    //	private static final int SCREEN_STATE_CHANGE = 0;
    private static final int UPDATE_TIMESHIFT_SEEKBAR = 1;
    private static final int UPDATE_TIMESHIFT_SECONDARY_SEEKBAR = 2;
    private static final int UPDATE_FLOAT_TIME = 3;
    private final int LAND = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
    private final int PORT = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
    private static final int RETRY_P2P_BUFFER_COUNT = 1; //p2p缓冲重试次数
    private int mP2pBufferCount; //p2p已经缓冲的次数

    private static final String AD_TAG = "ad_fragment";
    private String adInfoUrl;
    private AdFragment adFrag;

    public static final int TAB_NULL = 0;
    public static final int TAB_RECOM = 1;
    public static final int TAB_CHAN = 2;
    public static final int TAB_EPG = 3;
    public static final int TAB_EPI = 4;
    public static final int TAB_BEST = 5;
    public static final int TAB_DET = 6;

    /**
     * 点播视频当前播放的位置
     */
    public long currentPosition;
    /**
     * 右侧列表当前位置tab
     */
    private int currentTab = TAB_NULL;
    /**
     * 右侧列表当前隐藏的布局位置tab
     */
    private int currentTabData = TAB_NULL;

    private SparseArray<Fragment> mRightFrags;

    private boolean isDetached;
    /**
     * MediaPlayFragment是否调用了onPaused暂停播放了
     */
    private boolean isPaused;

    //fragment界面
//	private RelativeLayout mRlRoot;
    private RelativeLayout mRlRootGesture;
    private IjkVideoView mVideoView;
    private LinearLayout llAdArea;
    private LinearLayout llLoading;
    private ProgressBar pbProgressBar;

    //VideInfo相关信息
    /**
     * 传入播放器的videoInfo实体
     */
    private VideoInfo videoInfo;
    /**
     * 视频标题,通过videoInfo实体获取
     */
    private String videoTitle;
    /**
     * 是否直播播放类型
     */
    private boolean isLiveFlag;
    /**
     * 当前是否直播播放类型,用于判断播放器界面已创建的情况下点播与直播的切换
     */
    private boolean currentLiveFlag;
    /**
     * 是否全屏
     */
    private boolean isFullScreen;

    //点播相关
    /**
     * 点播vid
     */
    private String vId;
    /**
     * 获取点播数据的地址
     */
    private String videoVodPlayUrl;
    /**
     * 点播数据hls地址
     */
    private String videoVodHlsUrl;
    /**
     * 点播版权 1表示无版权不可播放，0表示可以播放
     */
    private int copyright;

    //直播相关
    /**
     * 新直播cdn地址
     */
    private String videoLiveUrl;
    /**
     * 旧直播地址，访问后带ipad和iphone字段
     */
    private String videoLivePlayUrl;
    /**
     * 直播频道ID,如cctv5
     */
    private String channelId;
    /**
     * 直播p2pUrl,如pa://cctv_p2p_hdcctv5
     */
    private String p2pPlayId;

    /**
     * epg地址,获取epg数据,只在支持时移的情况下才访问此地址
     */
    private String epgUrl;
    /**
     * 播放器最终播放地址，传入播放器底层的地址: mVideoView.setVideoPath(finalVideoUrl)
     */
    private String finalVideoUrl;

    /**
     * 当前手机摆放方向，横放 或者 竖放
     */
    private int currentOrientation;
    /**
     * 当前屏幕方向，横屏 或者 竖屏
     */
    private int currentScreen;
    /**
     * 是否根据手机摆放位置从竖屏到横屏
     */
    private boolean isAutoPortToLand;
    /**
     * 是否根据手机摆放位置从横屏到竖屏
     */
    private boolean isAutoLandToPort;

    //横竖屏事件监听器
    private OrientationEventListener mOrientationListener;
    private RotationObserver mRotationObserver;

    //播放器相关监听器 VideoView暴露
    private OnPreparedListener mOnPreparedListener;
    //	private OnInfoListener mOnInfoListener;
    private OnCompletionListener mOnCompletionListener;
    private OnErrorListener mOnErrorListener;
    private OnSurfaceListener mOnSurfaceListener;

    //播放器相关监听器MediaController暴露
    private OnVideoPlayListener mOnVideoPlayListener;
    private CustomerMediaController.OnHiddenListener mOnHiddenListener;
    private CustomerMediaController.OnShownListener mOnShownListener;
    private CustomerMediaController.OnClickPauseListener mOnClickPauseListener;

    //控制器相关监听器
    private OnClickListener mOnClickListener;
    private OnClickListener mFullOnClickListener;
    private MyHorizontalScrollView.OnScrollListener mOnTimeShiftScrollListener;
    private OnTouchListener mOnSeekBarTouchListener;
    private OnSeekBarChangeListener mOnTimeShiftSeekBarChangerListener;
    private OnSeekBarChangeListener mOnVerticalVolumeChangeListener;

    // controller视图
    private CustomerMediaController mMediaController;
    //半屏
    private View halfScreenControllerView;
    private ImageButton btnFullScreen;
    private ImageButton mBtnExit;
    private LinearLayout llTimeDisplay;
    //全屏
    private View fullScreenControllerView;
    private View liveControllerView;
    private View vodControllerView;
    private SeekBar seekbarHalf;
    private TextView mTvBite;
    private LinearLayout mLlPlayMode;
    private ImageButton mBtnVolume;
    private LinearLayout mLlBottom;
    private LinearLayout mLlBottomRight;
    private LinearLayout mLlVerticalVolume;
    private VerticalSeekBar mVsbVolume;
    private TextView mTvShare;
    private TextView mTvCollect;
    private ListView mLvPlayMode;
    private LinearLayout mLlLeft;
    private LinearLayout mLlRight;
    private ListView mLvRight;
    private TextView mTvTopRecommend;
    private TextView mTvTopChannel;
    private TextView mTvTopEpg;
    private TextView mTvTopEpiSelect;
    private TextView mTvTopBestSelect;
    private TextView mTvTopVodDetail;
    private LinearLayout mLlTimeShiftAdjust;
    private ImageButton mBtnTimeShiftAdd;
    private ImageButton mBtnTimeShiftCut;
    private LinearLayout mLlTimeShift;
    private MyHorizontalScrollView mHsvTimeShift;
    private LinearLayout mLlTimeShiftEpg;
    private LinearLayout mLlTimeShiftRuler;
    private SeekBar mSeekBarTimeShift;
    private TextView mTvFloatTime;
    private SeekBar mSeekBarFull;

    //时移相关变量
    private boolean isTimeShifting;
    private TimeShiftParams mTimeShiftParams;
    private TimeShiftEPG mTimeShiftEpg;
    private int currentType = Const.TIME_SHIFT_FOR_SECOND;
    private long currentPlayTime = System.currentTimeMillis();
    private long mTimeShiftBeginTime;
    private long mTimeShiftEndTime;
    private int mTimeShiftWidth;
    private int mTimeShiftHeight;
    private int mTimeShiftSbMax;
    private int mTimeShiftSeekSecondaryProgress;
    private int mTimeShiftSeekProgress;
    private boolean isFirstSmooth = true;
    protected int nowProgress;
    protected boolean isProgressLarger;//时移拖动是否大于当前时间
    private int mCountNotSupport;

    //播放器相关信息变量
    /**
     * 当前播放码率
     */
    private int currentRate;
    /**
     * 是否播放成功,加载状态条消失
     */
    private boolean isPlaySuccess;
    /**
     * 点播视频是否播放完成
     */
    private boolean isPlayComplete;
    /**
     * 是否点击了暂停按钮，视频处于暂停播放状态
     */
    private boolean isVideoPasued;
    /**
     * surfaceview是否创建成功
     */
    private boolean isSufaceCreated;
    /**
     * 暂停广告图片加载是否异常
     */
    private boolean isAdPausePhotoError;
//	private boolean isAdPlaying;
//	private boolean isAdError;

    /**
     * 当前广告类型,
     * Const.AD_CALL(播放前贴片) or  Const.AD_PAUSE(播放暂停广告图) or  Const.AD_AFTER(播放后贴片)
     */
    private int mCurrentAdCategory;

    private long startTime;
    private long startPlayTime;
    protected long p2pBufferTime;
    private CBoxP2P mP2pPlugin;

    //直播相关信息
    private VdnLiveInfo vdnLiveInfo;//vdn信息
    private Map<String, LiveEpg> mTimeShiftEpgList;//时移EPG列表
    private List<LiveEpg.Program> mEpgInfos;//当天EPG列表

    //码率相关信息
    private List<PlayMode> mModeList;
    private SparseArray<PlayMode> mModeSparse;
    private PlayModeAdaper mModeAdapter;

    private TelephonyManager mTelephonyManager;
    private PhoneStateListener mPhoneStateListener;
    private AudioManager mAudioManager;
    private int mMaxVolume;
    private int mCurrentVolume;

    private OnShareListener mOnShareListener;
    private OnCollectListener mOnCollectListener;
    private OnPlayerListener mOnPlayerListener;

    public int mP2pInitProgress;
    private CBoxP2P pPlugin;
    private ProgressDialog mDialog;

    private Map<Object, LivePolicy> mLivePolicy;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TIMESHIFT_SEEKBAR:
                    if (isPlaySuccess) {
                        mTimeShiftSeekProgress += 1;
                        mSeekBarTimeShift.setProgress(mTimeShiftSeekProgress);
                        mHandler.sendEmptyMessageDelayed(UPDATE_TIMESHIFT_SEEKBAR, mTimeShiftParams.dpToDate * 1000);
                    }
                    break;
                case UPDATE_TIMESHIFT_SECONDARY_SEEKBAR:
                    if (isPlaySuccess) {
                        mTimeShiftSeekSecondaryProgress += 1;
                        mSeekBarTimeShift.setSecondaryProgress(mTimeShiftSeekSecondaryProgress);
                        mHandler.sendEmptyMessageDelayed(UPDATE_TIMESHIFT_SECONDARY_SEEKBAR, mTimeShiftParams.dpToDate * 1000);
                    }

                    break;
                case UPDATE_FLOAT_TIME:
                    if (isPlaySuccess) {
                        currentPlayTime += 1000;
                        mTvFloatTime.setText(DateUtil.getTimeString(currentPlayTime, "HH:mm:ss"));
                        mHandler.sendEmptyMessageDelayed(UPDATE_FLOAT_TIME, 1000);
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 获取MediaPlayFrament实例
     *
     * @param videoInfo
     * @return
     */
    public static MediaPlayFragment newInstance(VideoInfo videoInfo) {
        MediaPlayFragment mpFrag = new MediaPlayFragment();
        Bundle args = new Bundle();
        args.putSerializable(VideoInfo.class.getName(), videoInfo);
        mpFrag.setArguments(args);
        return mpFrag;
    }


    /**
     * 获取MediaPlayFrament实例
     * 用于在Activity的onCreate()方法中添加播放器，没有传入有效的VideoInfo，
     * 防止在Activity创建后再添加fragment闪屏的问题
     *
     * @return
     */
    public static MediaPlayFragment newInstance() {
        MediaPlayFragment mpFrag = new MediaPlayFragment();
        return mpFrag;
    }


    /**
     * 设置VideoInfo, 当MediaPlayFragment被attach进来时调用
     * 调用后通过playVideo()方法播放视频
     *
     * @param videoInfo
     */
    public void setVideoInfo(VideoInfo videoInfo) {
        isDetached = true;
        this.videoInfo = videoInfo;
    }

    /**
     * 获取正在播放视频的信息
     */
    public VideoInfo getVideoInfo() {
        return videoInfo != null ? videoInfo : (VideoInfo) getArguments().getSerializable(VideoInfo.class.getName());
    }

    /**
     * 是否全屏
     *
     * @return
     */
    public boolean isFullScreen() {
        return isFullScreen;
    }


    @Override
    protected int setContentLayout() {
        // TODO Auto-generated method stub
        return R.layout.player_frag_layout;
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
//		LogUtil.i(TAG,"MediaPlayFragment onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
//		LogUtil.i(TAG,"MediaPlayFragment onCreate");

        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mRotationObserver = new RotationObserver(new Handler());
        mRotationObserver.startObserver();
        isFullScreen = !isPortraitScreen();
        currentOrientation = isFullScreen ? LAND : PORT;
        currentScreen = currentOrientation;

        mDialog = DialogUtil.getInstance().createProgress(mContext, R.string.p2p_ing);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
//		LogUtil.i(TAG,"MediaPlayFragment onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        LogUtil.d(TAG, "MediaPlayFragment onSaveInstanceState()");
        if (getActivity() == null) {
            LogUtil.d(TAG, "MediaPlayFragment onSaveInstanceState() getActivity()==null...");
            return;
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
//		LogUtil.i(TAG,"MediaPlayFragment onActivityCreated");

        if (!isDetached && getArguments() != null) {
            videoInfo = (VideoInfo) getArguments().getSerializable(VideoInfo.class.getName());
        }

        if (videoInfo == null) {
            LogUtil.i(TAG, "MediaPlayFragment onActivityCreated() getArguments().getSerializable(VideoInfo.class.getName()) is null....");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_get_play_info_null);
            return;
        }

        getPlayInfo();
        currentLiveFlag = isLiveFlag;

        setViewHeight(this.getView(), getPlayViewHeight());

        initDefault();

//        setP2pInitListener();
        setVideoListeners();

        initMediaController();

        //for time calc start
        startTime = System.currentTimeMillis();
        //for time calc end


        mLivePolicy = getCacheLivePolicy();
        if (isLiveFlag) {//直播类型时才重新获取 直播策略文件
            initJsonData(Const.LIVE_POLICY_PATH);
        }

        if (!isLiveFlag || mLivePolicy != null) {//如是不是直播类型(是点播)时 或者 直播策略文件(从缓存获取)不为空时 直播进入下一步操作
            doActivityCreated();
        }

        listeningPhoneState();
    }

    /**
     * 从缓存获取直播策略数据
     *
     * @return
     */
    private Map<Object, LivePolicy> getCacheLivePolicy() {
        Map<Object, LivePolicy> livePolicies = null;
        try {
            String livePolicy = SprefUtils.getInstance(mContext).getString(Const.SHAR_PREF_KEY_LIVE_POLICY);
            if (!TextUtils.isEmpty(livePolicy)) {
                livePolicies = ParseUtil.parseDataToMap(new JSONObject(livePolicy), "channel_info", "channel", LivePolicy.class);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return livePolicies;
    }

    private void doActivityCreated() {
//		getPlayInfo();

        //加载广告
        if (PlayerConfig.isAdSupport) {
            showAd(Const.AD_CALL);
        }

        updateMediaController();
        initNetData();

        if (PlayerConfig.isPortSupport && videoInfo.isPort() && videoInfo.isAutoScreen() && getRotationStatus() == 1) {
            mOrientationListener.enable();
        } else {
            mOrientationListener.disable();
        }
    }

    /**
     * 从传过来VideoInfo中获取播放信息
     */
    private void getPlayInfo() {
        // TODO Auto-generated method stub

        videoInfo.setTimeShift(videoInfo.isTimeShift() && PlayerConfig.isTimeShift);

        isLiveFlag = (videoInfo.getFlag() == Const.LIVE);
        videoTitle = videoInfo.getTitle();
        setPlayTitle(videoTitle);

        switch (videoInfo.getFlag()) {
            case Const.VOD:
                vId = videoInfo.getVid();
                videoVodPlayUrl = Const.PRE_VOD_URL + "pid=" + vId;
                LogUtil.i(TAG, "MediaPlayeFragment getPlayInfo() Const.VOD videoVodPlayUrl = " + videoVodPlayUrl);
                break;
            case Const.VODCACHE:
                vId = videoInfo.getVid();
                videoVodPlayUrl = videoInfo.getDetailUrl();
                LogUtil.i(TAG, "MediaPlayeFragment getPlayInfo() Const.VODCACHE videoVodPlayUrl = " + videoVodPlayUrl);
                break;
            case Const.LIVE:
                channelId = videoInfo.getChannelId();
                p2pPlayId = videoInfo.getP2pUrl();

                if (!TextUtils.isEmpty(channelId) && TextUtils.isEmpty(p2pPlayId)) {
                    p2pPlayId = Const.P2P_URL_PREFIX + channelId;
                } else if (TextUtils.isEmpty(channelId) && !TextUtils.isEmpty(p2pPlayId)) {
                    channelId = getChannelId(p2pPlayId);
                }
                if (videoInfo.isTimeShift() && !TextUtils.isEmpty(channelId)) {
                    epgUrl = Const.PRE_EPG_URL + "c=" + channelId;
                }

                isTimeShifting = false;
                if (!TextUtils.isEmpty(p2pPlayId)) {
                    videoLiveUrl = Const.PRE_VDN_URL + "channel=" + p2pPlayId;
                } else {
                    videoInfo.setTimeShift(false);
                    videoLivePlayUrl = videoInfo.getDetailUrl();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 通过P2pUrl获取channelId
     *
     * @param p2pUrl
     * @return
     */
    private String getChannelId(String p2pUrl) {
        return p2pUrl == null ? null : p2pUrl.substring(Const.P2P_URL_PREFIX.length());
    }


    /**
     * 通过VideoInfo开始播放video
     *
     * @param vInfo
     */
    public void playVideo(VideoInfo vInfo) {
        stopPlayer(true);
        llLoading.setVisibility(View.VISIBLE);//显示正在加载
        llLoading.setBackgroundColor(getResources().getColor(R.color.black));
        vInfo.setRate(videoInfo.getRate());
        vInfo.setAspectRatio(videoInfo.getAspectRatio());
        videoInfo = vInfo;
        getPlayInfo();

        if (mMediaController != null) {
            mMediaController.clear();
        }
        if (currentLiveFlag != isLiveFlag) {//点播变直播，或者直播变点播时，更新右侧视图和控制器
            currentLiveFlag = isLiveFlag;
            initDefault();
            updateMediaController();
        }

        initNetData();
    }

    /**
     * 手动禁止屏幕自动旋转
     */
    public void disableOrientation() {
        if (mOrientationListener != null) {
            mOrientationListener.disable();
        }
    }


    /**
     * 加载各网络数据
     */
    private void initNetData() {
        // TODO Auto-generated method stub
        switch (videoInfo.getFlag()) {
            case Const.VOD:
                if (!TextUtils.isEmpty(videoVodPlayUrl)) {
                    initJsonData(videoVodPlayUrl);
                } else if (!TextUtils.isEmpty(videoInfo.getDetailUrl())) {//点播地址为网络hls地址, 可直接播放
                    setVodPlayModeList(videoInfo);
                    play(videoInfo.getRate());
                } else {
                    LogUtil.i(TAG, "MediaPlayFragment initNetData() vodUrl is null.....");
                    playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
                }
                break;
            case Const.VODCACHE:
                //TODO 后续可合并点播和缓存播放，缓存播放时自动启动本地服务成功后组装播放地址
                if (!TextUtils.isEmpty(videoInfo.getDetailUrl())) {// 点播缓存播放, 可直接播放
                    setVodPlayModeList(videoInfo);
                    play(videoInfo.getRate());
                } else {
                    LogUtil.i(TAG, "MediaPlayFragment initNetData() vodCacheUrl is null.....");
                    playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
                }
                break;
            case Const.LIVE:
                if (!TextUtils.isEmpty(videoLiveUrl)) {
                    if (isLivePolicyOpen(channelId, Const.PLAYER_MODE_AUTO)
                            || isLivePolicyOpen(channelId, Const.PLAYER_MODE_SD)) {//直接策略允许时，才访问vdn获取直播地址,减少vdn负载
                        initJsonData(videoLiveUrl);
                    } else {//否则不再访问网络，直播只支持p2p播放
                        setLivePlayModeList(null);//vdn数据为空，码率列表只有p2p地址
                        play(Const.PLAYER_MODE_TS);//直接播放
                    }
                } else if (!TextUtils.isEmpty(videoLivePlayUrl)) {
                    initJsonData(videoLivePlayUrl);
                } else {
                    LogUtil.i(TAG, "MediaPlayFragment initNetData() liveUrl is null.....");
                    playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
                }
                if (!TextUtils.isEmpty(epgUrl)) {//时移不支持时，不去访问网络获取epg数据
                    initJsonData(epgUrl);
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void initDataSuccess(String url, JSONObject response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        try {
            if (url.equals(Const.LIVE_POLICY_PATH)) {
                if (mLivePolicy == null && isLiveFlag) {//如果直播策略缓存信息为空，
                    mLivePolicy = ParseUtil.parseDataToMap(response, "channel_info", "channel", LivePolicy.class);
                    doActivityCreated();
                }
                SprefUtils.getInstance(mContext).putString(Const.SHAR_PREF_KEY_LIVE_POLICY, response.toString());
            } else if (url.equals(videoLiveUrl)) {
                vdnLiveInfo = ParseUtil.parseDataToEntity(response, VdnLiveInfo.class);
                if (vdnLiveInfo == null) {
                    LogUtil.i(TAG, "MediaPlayFragment initDataOnSuccess() vdnLiveInfo is null.....");
                    playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_liveinfo_null);
                } else {
                    setLivePlayModeList(vdnLiveInfo);
                    play(currentRate == 0 ? videoInfo.getRate() : currentRate);
                }
            } else if (url.equals(videoLivePlayUrl)) {
                setLivePlayModeList(response.optString("ipad"), response.optString("iphone"));
                play(currentRate == 0 ? videoInfo.getRate() : currentRate);
            } else if (url.equals(videoVodPlayUrl)) {
                copyright = Utils.strToInt(response.optString("is_invalid_copyright"));
//				copyright = 1;// for test
                if (copyright == 1) {
                    LogUtil.i(TAG, "MediaPlayFragment initDataOnSuccess() vod video copyright is limit.....");
                    playError(Const.ERROR_INVALID_COPYRIGHT, R.string.error_invalid_copyright);
                    return;
                }
                videoVodHlsUrl = response.optString("hls_url");
                if (TextUtils.isEmpty(videoVodHlsUrl)) {
                    LogUtil.i(TAG, "MediaPlayFragment initDataOnSuccess() get vod hls_url is null.....");
                    playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
                    return;
                }
                videoInfo.setHls_url(videoVodHlsUrl);
                initJsonData(videoVodHlsUrl, true);
            } else if (url.equals(epgUrl)) {
                mTimeShiftEpgList = LiveEpg.getTimeShiftEpgList(response, channelId);
                if (isLiveFlag && isFullScreen && videoInfo.isTimeShift() && !mMediaController.isAdPlaying()) {
                    initTimeShift();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            LogUtil.i("zl", "MediaPlayFragment initDataSuccess() e = " + e.getMessage());
            initDataFailed(url, 102, getString(R.string.server_data_exception));
        }
    }

    @Override
    protected void initDataSuccess(String url, String response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        if (url.equals(videoVodHlsUrl)) {
            setVodPlayModeList(videoVodHlsUrl, response);
            play(videoInfo.getRate());
        }
    }

    @Override
    protected void initDataFailed(String url, int errorNo, String strMsg) {
        // TODO Auto-generated method stub
        super.initDataFailed(url, errorNo, strMsg);
        LogUtil.i(TAG, "MediaPlayFragment initDataFailed().... url = " + url);
        LogUtil.i(TAG, "MediaPlayFragment initDataFailed().... errMsg = " + strMsg);
        if (url.equals(Const.LIVE_POLICY_PATH)) {
            doActivityCreated();
        } else if (errorNo == Const.ERROR_REQUEST_NULL
                || errorNo == Const.ERROR_RESPONSE_NULL
                || errorNo == Const.ERROR_DATA_EXCEPTION
                || TextUtils.isEmpty(strMsg)) {//此四种访问失败与网络无关
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_exception);
        } else if (strMsg.contains("timed out") || strMsg.contains("Timeout")) {
            playError(Const.ERROR_TIMEOUT_EXCEPTION, R.string.error_net_data_time_out);//访问超时
        } else {
            playError(Const.ERROR_NET_EXCEPTION, R.string.error_net_exception);//其它,访问失败一律报网络异常错误
        }
    }

    /**
     * 设置videoview的各种监听器
     */
    private void setVideoListeners() {
        // mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);//在MediaContrller中已经监听了
//		mVideoView.setOnInfoListener(mOnInfoListener);//在MediaContrller中已经监听了
        mVideoView.setOnPreparedListener(mOnPreparedListener);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);
        mVideoView.setOnSurfaceListener(mOnSurfaceListener);
    }

    /**
     * 初始化MediaController并提前设置,
     * 播放器未成功播放时也予显示
     */
    private void initMediaController() {
        if (mMediaController == null) {
            mMediaController = new CustomerMediaController(mContext);
        }
        fullScreenControllerView = isLiveFlag ? liveControllerView : vodControllerView;
        mMediaController.setControllerView(isFullScreen ? fullScreenControllerView : halfScreenControllerView);
        mMediaController.setLiveFlag(isLiveFlag);
        mMediaController.setGestureView(mRlRootGesture);
        mMediaController.setVolumeView(mLlVerticalVolume);

        mMediaController.setOnVideoPlayListener(mOnVideoPlayListener);
        mMediaController.setOnHiddenListener(mOnHiddenListener);
        mMediaController.setOnShownListener(mOnShownListener);
        mMediaController.setOnClickPauseListener(mOnClickPauseListener);

        mVideoView.setMediaController(mMediaController);
    }

    /**
     * 设置播放控制器标题名称
     *
     * @param title
     */
    private void setPlayTitle(String title) {
        if (mMediaController != null) {
            mMediaController.setFileName(title);
        }
    }

    /**
     * 更新控制器,
     * 直播变成点播，点播变成直播，横屏到半屏，半屏到横屏
     */
    private void updateMediaController() {
        if (getActivity() != null) {
            updateMediaController(getResources().getConfiguration());
        }
    }

    /**
     * 更新控制器,
     * 直播变成点播，点播变成直播，横屏到半屏，半屏到横屏
     *
     * @param newConfig
     */
    private void updateMediaController(Configuration newConfig) {
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {//竖屏
            isFullScreen = false;
            setHalfScreenMediaController();
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {//否则横屏
            isFullScreen = true;
            setFullScreenMediaController();
        }
        setPlayTitle(videoTitle);
        setVolumeHeight();
    }

    /**
     * 更新MediaController
     *
     * @param type
     * @link #Const.PLAY_TYPE_PORT
     * @link #Const.PLAY_TYPE_LAND
     * @link #Const.PLAY_TYPE_RBC
     */
    public void updateMediaController(int type) {
        if (type == Const.PLAY_TYPE_RBC) {//右下角小屏播放
            setBottomRightMediaController();
        } else {
            updateMediaController();
        }
    }

    /**
     * 对右下角小窗播放时mediacontroller相关设置
     */
    private void setBottomRightMediaController() {

        mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//清除全屏
        setViewBottomRightLayout(this.getView());

        setViewGone(mLlPlayMode);//全屏码率窗口隐藏
        setViewGone(mLlVerticalVolume);//全屏音量窗口隐藏
        setViewGone(mLlTimeShiftAdjust);//全屏粒度按钮隐藏
        setViewGone(mLlRight);//全屏右侧列表隐藏

        currentTab = TAB_NULL;
        setTopRightTextSelected(TAB_NULL);
        setSelected(mTvBite, false);

        mVideoView.setMediaController(null);
        mVideoView.setVideoLayout(KooVideoView.VIDEO_LAYOUT_SCALE);

        LogUtil.i(TAG, "setBottomRightMediaController()  branch test test ");
    }

    /**
     * 设置视频右下角边小窗播放时的宽高
     *
     * @param iv
     */
    private void setViewBottomRightLayout(View iv) {
        LayoutParams layoutParams = iv.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = Utils.screenWidth(mContext) * 2 / 5;
            layoutParams.height = layoutParams.width * 9 / 16;
            iv.setLayoutParams(layoutParams);
        }
    }

    /**
     * 设置半屏时控制器的视图显示
     */
    private void setHalfScreenMediaController() {
        // TODO Auto-generated method stub
        mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//清除全屏
//		setViewHeight(mRlRoot, getPlayViewHeight());
        setViewHeight(this.getView(), getPlayViewHeight());


        setViewGone(mLlPlayMode);//全屏码率窗口隐藏
        setViewGone(mLlVerticalVolume);//全屏音量窗口隐藏
        setViewGone(mLlTimeShiftAdjust);//全屏粒度按钮隐藏
        setViewGone(mLlRight);//全屏右侧列表隐藏

        currentTab = TAB_NULL;
        setTopRightTextSelected(TAB_NULL);
        setSelected(mTvBite, false);

        if (mMediaController == null) {
            return;
        }
        mMediaController.setControllerView(halfScreenControllerView);
        mMediaController.setLiveFlag(isLiveFlag);
        mVideoView.setMediaController(mMediaController);
        mVideoView.setVideoLayout(KooVideoView.VIDEO_LAYOUT_FITXY);
        findHalfScreenControllerViews();
    }

    /**
     * 隐藏视图
     *
     * @param view
     */
    private void setViewGone(View view) {
        if (view != null) {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 设置全屏时控制器的视图显示
     */
    private void setFullScreenMediaController() {
        // TODO Auto-generated method stub
        mActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		setViewHeight(mRlRoot, getResources().getDisplayMetrics().heightPixels);
        setViewHeight(this.getView(), getResources().getDisplayMetrics().heightPixels);

        setViewGone(mLlPlayMode);//全屏码率窗口隐藏
        setViewGone(mLlVerticalVolume);//全屏音量窗口隐藏
        setViewGone(mLlTimeShiftAdjust);//全屏粒度按钮隐藏
        setViewGone(mLlRight);//全屏右侧列表隐藏

        if (mMediaController == null) {
            return;
        }

        fullScreenControllerView = isLiveFlag ? liveControllerView : vodControllerView;
        mMediaController.setControllerView(fullScreenControllerView);
        mMediaController.setLiveFlag(isLiveFlag);
        mVideoView.setMediaController(mMediaController);
        mVideoView.setVideoLayout(KooVideoView.VIDEO_LAYOUT_ZOOM);
        findFullScreenControllerViews();
        setFullScreenListener();
        if (isLiveFlag) {
//			Log.i(TAG,"videoInfo.isTimeShift()="+videoInfo.isTimeShift()+"_____________");
            if (videoInfo.isTimeShift()) {
                mLlTimeShift.setVisibility(View.VISIBLE);
                mLlTimeShiftAdjust.setVisibility(View.VISIBLE);
                mSeekBarFull.setVisibility(View.GONE);
                initTimeShift();
            } else {
                mLlTimeShift.setVisibility(View.GONE);
                mLlTimeShiftAdjust.setVisibility(View.GONE);
                mSeekBarFull.setVisibility(View.VISIBLE);
            }
        }
    }

    private void findHalfScreenControllerViews() {
        // TODO Auto-generated method stub
//		mBtnExit = (ImageButton)halfScreenControllerView.findViewById(R.id.ibtn_exit);
        btnFullScreen = (ImageButton) halfScreenControllerView.findViewById(R.id.ibtn_fullscreen);
        seekbarHalf = (SeekBar) halfScreenControllerView.findViewById(R.id.sb_player_seekbar);
        llTimeDisplay = (LinearLayout) halfScreenControllerView.findViewById(R.id.ll_time_display);
        if (isLiveFlag) {
            llTimeDisplay.setVisibility(View.GONE);
            seekbarHalf.setMax(1000);
            seekbarHalf.setProgress(1000);
            seekbarHalf.setThumb(getResources().getDrawable(R.drawable.player_thumb_transport));
            seekbarHalf.setEnabled(false);
        }

//		mBtnExit.setOnClickListener(mOnClickListener);
        btnFullScreen.setOnClickListener(mOnClickListener);
        mVsbVolume.setOnSeekBarChangeListener(mOnVerticalVolumeChangeListener);
    }

    private void findFullScreenControllerViews() {
        // TODO Auto-generated method stub

        mBtnExit = (ImageButton) fullScreenControllerView.findViewById(R.id.ibtn_exit);

        mTvShare = (TextView) fullScreenControllerView.findViewById(R.id.player_button_share);
        mTvShare.setVisibility(videoInfo.isShared() ? View.VISIBLE : View.GONE);
        mTvCollect = (TextView) fullScreenControllerView.findViewById(R.id.player_button_collect);


        mLlBottom = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_bottom);
        mLlBottomRight = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_bottom_right);
        //码率相关视图
        mTvBite = (TextView) fullScreenControllerView.findViewById(R.id.tv_bite_change);
        setBiteText();
        mLlPlayMode = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_play_mode);
        mLvPlayMode = (ListView) fullScreenControllerView.findViewById(R.id.lv_play_mode);


        mBtnVolume = (ImageButton) fullScreenControllerView.findViewById(R.id.ibtn_volume);

        //标题右侧按钮 推荐 频道 节目单
        mLlLeft = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_left);
        mLlRight = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_right);
//		mLvRight = (ListView)fullScreenControllerView.findViewById(R.id.lv_right);

        mTvTopRecommend = (TextView) fullScreenControllerView.findViewById(R.id.tv_top_recommend);
        mTvTopChannel = (TextView) fullScreenControllerView.findViewById(R.id.tv_top_channel);
        mTvTopEpg = (TextView) fullScreenControllerView.findViewById(R.id.tv_top_program);

        mTvTopEpiSelect = (TextView) fullScreenControllerView.findViewById(R.id.tv_top_epi_select);
        mTvTopBestSelect = (TextView) fullScreenControllerView.findViewById(R.id.tv_top_best_select);
        mTvTopVodDetail = (TextView) fullScreenControllerView.findViewById(R.id.tv_top_vod_detail);

        setTopRightButtonVisibility();

        //时移相关视图
        if (isLiveFlag) {
            mLlTimeShiftAdjust = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_time_shift_layout); //粒度调整区域
            mBtnTimeShiftAdd = (ImageButton) mLlTimeShiftAdjust.findViewById(R.id.ibtn_timeshift_add); //粒度增加
            mBtnTimeShiftCut = (ImageButton) mLlTimeShiftAdjust.findViewById(R.id.ibtn_timeshift_cut); //粒度减少

            mLlTimeShift = (LinearLayout) fullScreenControllerView.findViewById(R.id.ll_time_shift); //时移所有区域

            mHsvTimeShift = (MyHorizontalScrollView) mLlTimeShift.findViewById(R.id.hs_timeshift_scrollview);//epg列表区域
            mLlTimeShiftEpg = (LinearLayout) mLlTimeShift.findViewById(R.id.ll_timeshift_epg);   //epg列表区域
            mLlTimeShiftRuler = (LinearLayout) mLlTimeShift.findViewById(R.id.ll_time_shift_ruler);//刻度条区域
            mSeekBarTimeShift = (SeekBar) mLlTimeShift.findViewById(R.id.sb_timeshift_progressBar);   //时移seekbar
            mTvFloatTime = (TextView) mLlTimeShift.findViewById(R.id.tv_timeshit_float_time);

            //隐藏时移 时显示的seekbar
            mSeekBarFull = (SeekBar) fullScreenControllerView.findViewById(R.id.sb_live);   //直播无时移 时默认seekbar 不可点击
            mSeekBarFull.setEnabled(false);

            //直播时隐藏收藏按钮
            mTvCollect.setVisibility(View.GONE);

        } else {
            updateCollectView(videoInfo.isHasCollected());
            mTvCollect.setVisibility(videoInfo.isCollected() ? View.VISIBLE : View.GONE);
        }

        boolean isLeftGone = mTvShare.getVisibility() == View.GONE && mTvCollect.getVisibility() == View.GONE;
        mLlLeft.setVisibility(isLeftGone ? View.GONE : View.VISIBLE);
    }

    private void setFullScreenListener() {
        // TODO Auto-generated method stub
        mFullOnClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mMediaController.show();
                int id = v.getId();
                if (id == R.id.ibtn_exit) {
                    if (PlayerConfig.isPortSupport && videoInfo.isPort()) {
                        setPortrait();
                    } else {
                        mActivity.finish();
                    }
                } else if (id == R.id.tv_bite_change) {
                    popupModeView();
                } else if (id == R.id.ibtn_volume) {
                    popupVolumeView();
                } else if (id == R.id.player_button_share) {
                    if (mOnShareListener != null) {
                        mOnShareListener.onShare(videoInfo);
                    }
                } else if (id == R.id.player_button_collect) {
                    //TODO 收藏
                    if (mOnCollectListener != null) {
                        mOnCollectListener.onCollect(videoInfo);
                    }

                } else if (id == R.id.ibtn_timeshift_add) {
                    switch (currentType) {
                        case Const.TIME_SHIFT_FOR_DAY:
                            createTimeShiftEPG(Const.TIME_SHIFT_FOR_HOUR);
                            break;
                        case Const.TIME_SHIFT_FOR_HOUR:
                            createTimeShiftEPG(Const.TIME_SHIFT_FOR_SECOND);
                            break;
                        case Const.TIME_SHIFT_FOR_SECOND:
                            break;
                        default:
                            break;
                    }
                } else if (id == R.id.ibtn_timeshift_cut) {
                    switch (currentType) {
                        case Const.TIME_SHIFT_FOR_DAY:
                            break;
                        case Const.TIME_SHIFT_FOR_HOUR:
                            createTimeShiftEPG(Const.TIME_SHIFT_FOR_DAY);
                            break;
                        case Const.TIME_SHIFT_FOR_SECOND:
                            createTimeShiftEPG(Const.TIME_SHIFT_FOR_HOUR);
                            break;
                        default:
                            break;
                    }
                } else if (id == R.id.tv_top_recommend) {
                    showTopRightInfo(TAB_RECOM);
                } else if (id == R.id.tv_top_channel) {
                    showTopRightInfo(TAB_CHAN);
                } else if (id == R.id.tv_top_program) {
                    showTopRightInfo(TAB_EPG);
                } else if (id == R.id.tv_top_epi_select) {
                    showTopRightInfo(TAB_EPI);
                } else if (id == R.id.tv_top_best_select) {
                    showTopRightInfo(TAB_BEST);
                }

            }
        };
        mOnTimeShiftScrollListener = new MyHorizontalScrollView.OnScrollListener() {

            @Override
            public void onScroll(int scrollX) {
                // TODO Auto-generated method stub
                mMediaController.show();
            }

        };

        mOnTimeShiftSeekBarChangerListener = new OnSeekBarChangeListener() {

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                nowProgress = seekBar.getProgress();
                // TODO Auto-generated method stub
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

                if (vdnLiveInfo == null || vdnLiveInfo.getHls_url() == null
                        || TextUtils.isEmpty(vdnLiveInfo.getHls_url().getHls4())) {
                    mSeekBarTimeShift.setProgress(mTimeShiftSeekSecondaryProgress);
                    mTimeShiftSeekProgress = mTimeShiftSeekSecondaryProgress;
                    currentPlayTime = mTimeShiftBeginTime + mTimeShiftSeekProgress * mTimeShiftParams.dpToDate * 1000;
                    setFloatTimePosition(mTimeShiftSeekProgress, DateUtil.getTimeString(currentPlayTime, "HH:mm:ss"));

                    switch (mCountNotSupport) {
                        case 0:
                            ToastUtil.showToast(mContext, R.string.error_not_support_timeshift1, Toast.LENGTH_SHORT);
                            break;
                        case 1:
                        case 2:
                            ToastUtil.showToast(mContext, R.string.error_not_support_timeshift2, Toast.LENGTH_SHORT);
                            break;
                        default:
                            ToastUtil.showToast(mContext, R.string.error_not_support_timeshift3, Toast.LENGTH_SHORT);
                            break;
                    }
                    if (mCountNotSupport++ >= 5) {
                        mSeekBarTimeShift.setEnabled(false);
                    }

                    return;
                }

                int newProgress = seekBar.getProgress();
                if (newProgress != nowProgress && newProgress <= mTimeShiftSeekSecondaryProgress) {
                    stopPlayer(false);
                    isTimeShifting = true;
                    llLoading.setVisibility(View.VISIBLE);//显示正在加载
                    String hls4 = vdnLiveInfo.getHls_url().getHls4();

                    /*****匹配时移地址带?的情况*******/
                    if (hls4.indexOf("?") >= 0) {
                        hls4 += "&";
                    } else {
                        hls4 += "?";
                    }
//					normalPlay(hls4+"begintimeback="+ currentPlayTime);
//					currentPlayTime=31729025;
                    normalPlay(hls4 + "begintimeback=" + currentPlayTime);
//					Log.i(TAG,"vdnLiveInfo.getHls_url().getHls4()+时移地址="+hls4+"begintimeback="+ currentPlayTime+"_______________");


//					normalPlay(hls4+"?name="+channelId+"&begintimeabs=" + currentPlayTime);
                    mHandler.removeMessages(UPDATE_FLOAT_TIME);
                    mHandler.removeMessages(UPDATE_TIMESHIFT_SEEKBAR);
                }
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub
                if (fromUser) {
                    mMediaController.show();
                    if (progress >= mTimeShiftSeekSecondaryProgress) {
                        mSeekBarTimeShift.setProgress(mTimeShiftSeekSecondaryProgress);
                        mTimeShiftSeekProgress = mTimeShiftSeekSecondaryProgress;
                        isProgressLarger = true;
                    } else {
                        mTimeShiftSeekProgress = progress;
                    }
                    currentPlayTime = mTimeShiftBeginTime + mTimeShiftSeekProgress * mTimeShiftParams.dpToDate * 1000;
//					Log.i(TAG, "onProgressChanged--时移当前时间："+currentPlayTime+"++++++++++");
                }

                setFloatTimePosition(mTimeShiftSeekProgress, DateUtil.getTimeString(currentPlayTime, "HH:mm:ss"));

				/*if(!fromUser || mTimeShiftSeekProgress != mTimeShiftSeekSecondaryProgress || mProgressLarger){
                }*/
            }
        };
        mOnSeekBarTouchListener = new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_UP:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                    default:
                        break;
                }
                return false;
            }
        };

        mBtnExit.setOnClickListener(mFullOnClickListener);
        mTvBite.setOnClickListener(mFullOnClickListener);
        mBtnVolume.setOnClickListener(mFullOnClickListener);
        mVsbVolume.setOnSeekBarChangeListener(mOnVerticalVolumeChangeListener);
        if (mTvCollect != null) {
            mTvCollect.setOnClickListener(mFullOnClickListener);
        }
        if (mTvShare != null) {
            mTvShare.setOnClickListener(mFullOnClickListener);
        }

        if (isLiveFlag) {
            mHsvTimeShift.setOnScrollListener(mOnTimeShiftScrollListener);//监听滑动时，一直显示mediaController
            mSeekBarTimeShift.setOnSeekBarChangeListener(mOnTimeShiftSeekBarChangerListener);
            if (videoInfo.isTimeShift()) {
                mSeekBarTimeShift.setOnTouchListener(mOnSeekBarTouchListener);
            }
            mBtnTimeShiftAdd.setOnClickListener(mFullOnClickListener);
            mBtnTimeShiftCut.setOnClickListener(mFullOnClickListener);

            mTvTopRecommend.setOnClickListener(mFullOnClickListener);
            mTvTopChannel.setOnClickListener(mFullOnClickListener);
            mTvTopEpg.setOnClickListener(mFullOnClickListener);
        } else {
//			mBtnPlayPre.setOnClickListener(mFullOnClickListener);
//			mBtnPlayNext.setOnClickListener(mFullOnClickListener);

            mTvTopEpiSelect.setOnClickListener(mFullOnClickListener);
            mTvTopBestSelect.setOnClickListener(mFullOnClickListener);
            mTvTopVodDetail.setOnClickListener(mFullOnClickListener);
            mTvTopRecommend.setOnClickListener(mFullOnClickListener);
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);

        LogUtil.i(TAG, "MediaPlayFragment onConfigurationChanged");
        if (this.isAdded() && !this.isDetached()) {
            updateMediaController(newConfig);
        }
    }


    @Override
    protected void findViews(View rootView) {
        // TODO Auto-generated method stub
        super.findViews(rootView);

//		mRlRoot = (RelativeLayout) rootView.findViewById(R.id.rl_root_video);
        mVideoView = (IjkVideoView) rootView.findViewById(R.id.cmv_surfaceView);
        llAdArea = (LinearLayout) rootView.findViewById(R.id.ll_ad_area);
        llLoading = (LinearLayout) rootView.findViewById(R.id.ll_loading);
        pbProgressBar = (ProgressBar) rootView.findViewById(R.id.pb_progressBar);

        mRlRootGesture = (RelativeLayout) rootView.findViewById(R.id.rl_root_gesture);

        //音量键
        mLlVerticalVolume = (LinearLayout) rootView.findViewById(R.id.ll_vetical_volume);
        setVolumeHeight();
        mVsbVolume = (VerticalSeekBar) rootView.findViewById(R.id.vsb_volume);
        mVsbVolume.setMax(mMaxVolume);

        halfScreenControllerView = View.inflate(mContext, R.layout.player_control_halfscreen, null);
        liveControllerView = View.inflate(mContext, R.layout.player_control_live_fullscreen, null);
        vodControllerView = View.inflate(mContext, R.layout.player_control_vod_fullscreen, null);
    }

    private void setLoadingLayout() {
        if (getActivity() == null) {
            return;
        }
        llLoading.setBackgroundColor(getResources().getColor(R.color.transparent));
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) pbProgressBar.getLayoutParams();
        layoutParams.width = LayoutParams.WRAP_CONTENT;
        layoutParams.height = LayoutParams.WRAP_CONTENT;
        pbProgressBar.setLayoutParams(layoutParams);
    }

    /**
     * 根据是否横竖屏设置音量条的高度
     */
    private void setVolumeHeight() {
        if (getActivity() == null) {
            return;
        }
        int horzizontalHeight = getResources().getDimensionPixelOffset(R.dimen.volume_height_horizontal);
        int verticalHeight = getResources().getDimensionPixelOffset(R.dimen.volume_height_vertical);
        if (mVsbVolume != null) {
            LayoutParams layoutParams = mVsbVolume.getLayoutParams();
            layoutParams.height = isFullScreen ? horzizontalHeight : verticalHeight;
            mVsbVolume.setLayoutParams(layoutParams);
        }
    }

    @Override
    protected void setListensers() {
        // TODO Auto-generated method stub
        super.setListensers();
        mOnVideoPlayListener = new OnVideoPlayListener() {

            @Override
            public void onVideoLoading() {
                // TODO Auto-generated method stub
                llLoading.setVisibility(View.VISIBLE);
                if (!Utils.isNetConneted(mContext) && videoInfo.getFlag() != Const.VODCACHE) {
                    LogUtil.i(TAG, "MediaPlayFragment onVideoLoading() net is disconnected....");
                    playError(Const.ERROR_NET_EXCEPTION, R.string.error_net_exception);
                }
            }

            @Override
            public void onVideoPlay() {
                // TODO Auto-generated method stub

                //for time calc start
                long nowTime = System.currentTimeMillis();
                if (p2pBufferTime == 0) {
                    LogUtil.i(TAG, "视频地址缓冲时长：" + (nowTime - startPlayTime));
                } else {
                    LogUtil.i(TAG, "视频地址缓冲时长：" + (nowTime - p2pBufferTime));
                }
                LogUtil.i(TAG, "播放总时长：" + (nowTime - startTime));
                //for time calc end

                isPlaySuccess = true;
                isPlayComplete = false;
                setLoadingLayout();

                if (mOnPlayerListener != null) {
                    mOnPlayerListener.onPlayStart();
                }
                if (isVideoPasued || isPaused) {
                    LogUtil.i(TAG, "mVideoView.pause()");
                    mVideoView.pause();
                    if (mCurrentAdCategory != Const.AD_CALL &&
                            mCurrentAdCategory != Const.AD_AFTER) {//解决暂停时home键退出重新进入后，缓冲成功
                        llLoading.setVisibility(View.GONE);
                    }
                    if (mCurrentAdCategory == 0) {
                        mMediaController.show();
                    }
                } else {
                    llLoading.setVisibility(View.GONE);
//						mMediaController.show();
                    if (isLiveFlag && isFullScreen && videoInfo.isTimeShift()) {
                        smoothScrollView();
                        mHandler.removeMessages(UPDATE_FLOAT_TIME);
                        mHandler.sendEmptyMessage(UPDATE_FLOAT_TIME);
                        if (mTimeShiftParams != null) {
                            mHandler.removeMessages(UPDATE_TIMESHIFT_SEEKBAR);
                            mHandler.sendEmptyMessageDelayed(UPDATE_TIMESHIFT_SEEKBAR, mTimeShiftParams.dpToDate * 1000);
                            mHandler.removeMessages(UPDATE_TIMESHIFT_SECONDARY_SEEKBAR);
                            mHandler.sendEmptyMessageDelayed(UPDATE_TIMESHIFT_SECONDARY_SEEKBAR, mTimeShiftParams.dpToDate * 1000);
                        }
                    }
                }
            }

            @Override
            public void onVideoPlayComplete() {
                // TODO Auto-generated method stub
//				LogUtil.i(TAG,"onVideoPlayComplete....onVideoPlayComplete");
                if (!isLiveFlag && mOnPlayerListener != null) {
                    mOnPlayerListener.onPlayComplete();
                }
            }
        };
        mOnPreparedListener = new OnPreparedListener() {

            @Override
            public void onPrepared(IMediaPlayer mp) {
                // TODO Auto-generated method stub
//				LogUtil.e(TAG, "MediaPlayFragment:CntvPlayer videoview  onPrepared .....");
                mVideoView.start();

            }
        };
        mOnCompletionListener = new OnCompletionListener() {

            @Override
            public void onCompletion(IMediaPlayer mp) {
                // TODO Auto-generated method stub
                LogUtil.i(TAG, "mOnCompletionListener....mOnCompletionListener");
                currentPosition = 0;
                if (isLiveFlag) {//直播卡顿时会调用onCompletion方法，重新播放
                    if (!Utils.isNetConneted(mContext)) {
                        LogUtil.i(TAG, "MediaPlayFragment  onCompletion() net is disconnected...");
                        playError(Const.ERROR_NET_EXCEPTION, R.string.error_net_exception);
                        return;
                    }
                    if (isTimeShifting) {
                        ToastUtil.showToast(mContext, R.string.timeshift_renew_live, Toast.LENGTH_SHORT);
                        isTimeShifting = false;
                        createTimeShiftEPG(currentType);
                    }
                    if (!mVideoView.isPlaying()) {
                        llLoading.setVisibility(View.VISIBLE);
                        stopPlayer(false);
                        play(videoInfo.getRate());
                    }
                } else if (PlayerConfig.isAdSupport && hasAfterAd()) {
                    llLoading.setVisibility(View.VISIBLE);
                    isPlayComplete = true;
                    stopPlayer(true);
                    AnimController.getInstance().fadeOut(mVideoView);
                    showAd(Const.AD_AFTER);
                } else if (mOnPlayerListener != null) {
                    isPlayComplete = true;
                    mOnPlayerListener.onPlayComplete();
                }
            }
        };

        mOnErrorListener = new OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                // TODO Auto-generated method stub
                LogUtil.i(TAG, "MediaPlayFragment onErrorListener....");
                stopPlayer(false);

                if (isLiveFlag && currentRate == Const.PLAYER_MODE_TS) {
                    if (mP2pBufferCount < RETRY_P2P_BUFFER_COUNT) {
                        LogUtil.i(TAG, "MediaPlayFragment p2p play onErrorListener(), p2p play again ....");
                        mP2pBufferCount++;
                        play(videoInfo.getRate());
                    } else {
                        CBoxStaticParam.P2P_INIT_SUCCESS_STATE = false;
                        convertPlay(Const.PLAYER_MODE_TS);
                    }
                } else {
                    convertPlay(currentRate);
                }

                return true;
            }
        };
        mOnSurfaceListener = new OnSurfaceListener() {


            @Override
            public void onSurfaceCreate() {
                // TODO Auto-generated method stub
                isSufaceCreated = true;

                llLoading.setVisibility(View.VISIBLE);//显示正在加载
                LogUtil.i("zl", "MediaPlayFragment onSurfaceCreate finalVideoUrl = " + finalVideoUrl);
                if (!TextUtils.isEmpty(finalVideoUrl)) {
                    if (isLiveFlag && currentRate == Const.PLAYER_MODE_TS) {
                        p2pPlay(p2pPlayId);
                    } else {
                        normalPlay(finalVideoUrl);
                    }
                }
            }

            @Override
            public void onSurfaceDestroyed() {
                // TODO Auto-generated method stub
                isSufaceCreated = false;
                if (mMediaController != null) {
                    mMediaController.hide();
                }
                stopPlayer(false, false);
                mP2pBufferCount = 0;
            }
        };

        mOnClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int id = v.getId();
                if (id == R.id.ibtn_fullscreen) {
                    setLandscape();
                } else if (id == R.id.ibtn_exit) {
                    if (isPortraitScreen()) {
                        mActivity.finish();
                        mActivity.overridePendingTransition(R.anim.base_fade_in, R.anim.base_push_right_out);
                    } else {
                        setLandscape();
                    }
                }
            }
        };

        mOnHiddenListener = new CustomerMediaController.OnHiddenListener() {

            @Override
            public void onHidden() {
                // TODO Auto-generated method stub

                currentTab = TAB_NULL;
                setTopRightTextSelected(TAB_NULL);
                //码率按钮恢复默认
                setSelected(mTvBite, false);
				/*//全屏码率窗口隐藏
				AnimController.getInstance().scaleOut(mLlPlayMode,200,0);
				//全屏音量窗口隐藏
				AnimController.getInstance().scaleOut(mLlVerticalVolume,200,0);
				//全屏右边列表窗口隐藏
				AnimController.getInstance().slideRightOut(mLlRight, 350, 0);
				//全屏粒度按钮隐藏
				if(isLiveFlag && videoInfo.isTimeShift()){
					AnimController.getInstance().slideBottomOut(mLlTimeShiftAdjust, 350, 0);
				}*/
            }
        };

        mOnShownListener = new CustomerMediaController.OnShownListener() {

            @Override
            public void onShown() {
                // TODO Auto-generated method stub
                if (isLiveFlag && isFullScreen && videoInfo.isTimeShift()) {
                    AnimController.getInstance().fadeIn(mLlTimeShiftAdjust);
//					AnimController.getInstance().slideBottomIn(mLlTimeShiftAdjust, 100, 0);
                }
            }
        };
        mOnClickPauseListener = new CustomerMediaController.OnClickPauseListener() {

            @Override
            public void onClickPause(boolean isPaused) {
                // TODO Auto-generated method stub
//				isVideoPasued = !mVideoView.isPlaying();
                isVideoPasued = isPaused;
                if (mOnPlayerListener != null) {
                    mOnPlayerListener.onPlayPauseChanged(isVideoPasued);
                }
                if (PlayerConfig.isAdSupport) {
                    handlePauseAd();
                }
            }
        };

        mOrientationListener = new OrientationEventListener(mContext) {
            @Override
            public void onOrientationChanged(int rotation) {
                if (((rotation >= 0) && (rotation <= 30))
                        || (rotation >= 330) || (rotation > 170) && (rotation < 190)) {// 设置竖屏
                    isAutoLandToPort = true;
                    if (isAutoPortToLand && currentScreen != PORT) {
                        setActivityOriention(PORT);
                    }
                } else if (((rotation >= 230) && (rotation <= 310))
                        || ((rotation >= 70) && (rotation <= 120))) {// 设置横屏
                    isAutoPortToLand = true;
                    if (isAutoLandToPort && currentScreen != LAND) {
                        setActivityOriention(LAND);
                    }
                }
            }
        };

        mOnVerticalVolumeChangeListener = new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub
//				LogUtil.i("zl","onProgressChanged fromUser = " + fromUser);
                if (fromUser) {
                    setVolume(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
                mMediaController.show();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
                mMediaController.show();
            }
        };
    }

    /**
     * 将fragment移除
     */
    public void removeSelf() {
        FragmentTransaction mFragTransaction = getFragTran();
        mFragTransaction.remove(this);
        mFragTransaction.commitAllowingStateLoss();
    }

    /**
     * 获取FragmentTransaction
     *
     * @return
     */
    public FragmentTransaction getFragTran() {
        FragmentTransaction mFragTransaction = null;
        if (getParentFragment() == null) {
            mFragTransaction = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction();
        } else {
            mFragTransaction = getParentFragment().getChildFragmentManager().beginTransaction();
        }
        return mFragTransaction;
    }

    /**
     * 弹框提示播放错误
     */
    private void playError(int errNo, int errMsgId) {
        if (getActivity() == null) {
            return;
        }
        playError(errNo, getString(errMsgId));
    }

    /**
     * 弹框提示播放错误
     */
    private void playError(int errNo, String errMsg) {
        // TODO Auto-generated method stub
        if (getActivity() == null) {
            return;
        }

        if (adFrag != null) {
            adFrag.removeSelf();
        }
        if (mOnPlayerListener != null) {
            mOnPlayerListener.onPlayError(errNo, errMsg);
        } else {
            removeSelf();
            errMsg = TextUtils.isEmpty(errMsg) ? getString(R.string.error_exception) : errMsg;
            new AlertDialog.Builder(mContext).setTitle("提示").setMessage(errMsg)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                            mActivity.finish();
                        }
                    }).show();
        }

    }
    /***********************************start 屏幕控制相关方法 start*******************************************************************/
    /**
     * 设置view的高度
     *
     * @param iv
     * @param height
     */
    private void setViewHeight(View iv, int height) {
        LayoutParams layoutParams = iv.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = LayoutParams.MATCH_PARENT;
            layoutParams.height = height;
            iv.setLayoutParams(layoutParams);
        }
    }

    /**
     * 获取手机屏幕宽度3/4大小的值
     *
     * @return
     */
    private int getPlayViewHeight() {
        float aspectRadio = 0;
        if (videoInfo == null || videoInfo.getAspectRatio() == 0) {
            aspectRadio = Const.ASPECT_RATIO_SMALL;
        } else {
            aspectRadio = videoInfo.getAspectRatio();
        }
        int screenWidth = Utils.screenWidth(mContext);
        int height = (int) (screenWidth / aspectRadio);
        return height;
    }

    /***********************************end 屏幕控制相关方法 end*******************************************************************/

    /***********************************start 直播时移相关方法 start*******************************************************************/


    /**
     * 初始化时移相关变量
     */
    private void initTimeShift() {
        if (mTimeShiftParams == null && !isDetached) {
            mTimeShiftParams = new TimeShiftParams(mHsvTimeShift);
        }
        if (mTimeShiftEpg == null && !isDetached) {
            mTimeShiftEpg = new TimeShiftEPG(mContext, mLlTimeShiftEpg);//初始化 EPG创建方法
        }
        createTimeShiftEPG(currentType);
        mSeekBarTimeShift.setEnabled(true);

//		极速码率下不能时移
//		if(videoInfo.getRate() == Const.PLAYER_MODE_TS){
//			mSeekBarTimeShift.setEnabled(false);
//		}else{
//			mSeekBarTimeShift.setEnabled(true);
//		}
    }


    /**
     * 设置时移粒度
     *
     * @param type
     */
    private void createTimeShiftEPG(int type) {

        long nowTime = System.currentTimeMillis();
        currentPlayTime = (currentPlayTime != 0 && isTimeShifting) ? currentPlayTime : nowTime;

        switch (type) {
            case Const.TIME_SHIFT_FOR_SECOND:
                mTimeShiftParams.setSecond();
                mTimeShiftBeginTime = DateUtil.getDayStartMilliseconds(currentPlayTime);
                break;
            case Const.TIME_SHIFT_FOR_HOUR:
                mTimeShiftParams.setHour();
                mTimeShiftBeginTime = DateUtil.getDayStartMilliseconds() - (mTimeShiftParams.dayToCanvas - 1) * 24 * 60 * 60 * 1000;//往前6天0点毫秒值
                break;
            case Const.TIME_SHIFT_FOR_DAY:
                mTimeShiftParams.setDay();
                mTimeShiftBeginTime = DateUtil.getDayStartMilliseconds() - (mTimeShiftParams.dayToCanvas - 1) * 24 * 60 * 60 * 1000;//往前6天0点毫秒值
                break;
            default:
                break;
        }
        //设置当前粒度类型
        currentType = type;

        //获取正在播放时段当天直播节目列表
        if (mTimeShiftEpgList != null) {
            mEpgInfos = mTimeShiftEpgList.get(DateUtil.getTimeString(mTimeShiftBeginTime)).getProgram();
        }

        //重新设置时移视图相关变量
        mTimeShiftEndTime = mTimeShiftBeginTime + mTimeShiftParams.secondToCanvas * 1000;
        mTimeShiftWidth = mTimeShiftParams.secondToCanvas / mTimeShiftParams.dpToDate;
        mTimeShiftHeight = getResources().getDimensionPixelOffset(R.dimen.time_shift_seek_layout_height);
        setTimeShiftLayout();

        //重新设置时移seekbar相关变量
        mTimeShiftSbMax = mTimeShiftWidth;

        mTimeShiftSeekSecondaryProgress = (int) ((nowTime - mTimeShiftBeginTime) / (1000 * mTimeShiftParams.dpToDate));
        mTimeShiftSeekProgress = (int) ((currentPlayTime - mTimeShiftBeginTime) / (1000 * mTimeShiftParams.dpToDate));

        mTimeShiftSeekProgress = (mTimeShiftSeekProgress != 0 && isTimeShifting) ? mTimeShiftSeekProgress : mTimeShiftSeekSecondaryProgress;

        mSeekBarTimeShift.setMax(mTimeShiftSbMax);
        mSeekBarTimeShift.setSecondaryProgress(mTimeShiftSeekSecondaryProgress);
        mSeekBarTimeShift.setProgress(mTimeShiftSeekProgress);

        //重新设置漂浮时间位置并发送消息定时更新
        setFloatTimePosition(mTimeShiftSeekProgress, DateUtil.getTimeString(currentPlayTime, "HH:mm:ss"));

        if (isPlaySuccess) {
            mHandler.removeMessages(UPDATE_FLOAT_TIME);
            mHandler.sendEmptyMessageDelayed(UPDATE_FLOAT_TIME, 1000);
            //发送消息更新时移seekbar
            mHandler.removeMessages(UPDATE_TIMESHIFT_SEEKBAR);
            mHandler.sendEmptyMessageDelayed(UPDATE_TIMESHIFT_SEEKBAR, mTimeShiftParams.dpToDate * 1000);
            mHandler.removeMessages(UPDATE_TIMESHIFT_SECONDARY_SEEKBAR);
            mHandler.sendEmptyMessageDelayed(UPDATE_TIMESHIFT_SECONDARY_SEEKBAR, mTimeShiftParams.dpToDate * 1000);

        }

        //判断是否创建epg列表
        if (type == Const.TIME_SHIFT_FOR_SECOND) {
            createEpgView();
        } else {
            clearEpgView();
        }

        //创建刻度标尺
        createRulerView();

        smoothScrollView();

    }

    /**
     * 移动MyHorizontalScrollView位置居中
     */
    private void smoothScrollView() {
        if (mHsvTimeShift == null) {
            return;
        }
        mHsvTimeShift.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                mHsvTimeShift.smoothScrollTo(mTimeShiftSeekProgress - Utils.screenWidth(mContext) / 2, 0);
                isFirstSmooth = false;
            }
        }, isFirstSmooth ? 500 : 0);
    }


    /**
     * 设置时移布局的宽度
     */
    private void setTimeShiftLayout() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mSeekBarTimeShift.getLayoutParams();
        layoutParams.width = mTimeShiftWidth;
        mSeekBarTimeShift.setLayoutParams(layoutParams);
    }

    /**
     * 设置漂浮时间的位置
     *
     * @param leftMargin
     * @param text
     */
    private void setFloatTimePosition(int leftMargin, String text) {
        mTvFloatTime.setText(text);
        mTvFloatTime.measure(0, 0);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mTvFloatTime.getLayoutParams();
        layoutParams.leftMargin = leftMargin - mTvFloatTime.getMeasuredWidth() / 2;
        mTvFloatTime.setLayoutParams(layoutParams);
    }

    /**
     * 创建刻度条
     */
    private void createRulerView() {
        mLlTimeShiftRuler.removeAllViews();
        RulerView ruler = new RulerView(mContext, mTimeShiftWidth, mTimeShiftBeginTime, mTimeShiftParams);
        mLlTimeShiftRuler.addView(ruler);
    }

    /**
     * 创建epg列表
     */
    private void createEpgView() {
        mTimeShiftEpg.create(mTimeShiftEpgList, mTimeShiftParams, mTimeShiftBeginTime, mTimeShiftEndTime, null);
    }

    /**
     * 清除epg列表
     */
    private void clearEpgView() {
        mTimeShiftEpg.clear(mTimeShiftParams);
    }


    /***********************************end 直播时移相关方法 end******************************************************************************/
    /***********************************start 播放器播放相关方法 start******************************************************************************/

    /**
     * 根据码率选择如何播放,
     *
     * @param rate
     */
    private void play(int rate) {
        if (mModeSparse == null || mModeSparse.size() == 0) {
            LogUtil.i(TAG, "MediaPlayFragment  play() mModeSparse data null....");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
            return;
        }
        //for time calc start
        startPlayTime = System.currentTimeMillis();//用来记录播放缓冲时间
        LogUtil.i(TAG, "加载播放地址时长: " + (startPlayTime - startTime));
        //for time calc end

        if (isLiveFlag) {
            if (mModeSparse.indexOfKey(rate) >= 0) {
                if (rate == Const.PLAYER_MODE_TS) {
                    p2pPlay(mModeSparse.get(rate).getPlayUrl());
                } else {
                    normalPlay(mModeSparse.get(rate).getPlayUrl());
                }
            } else if (rate != Const.PLAYER_MODE_SD && mModeSparse.indexOfKey(Const.PLAYER_MODE_SD) >= 0) {
                videoInfo.setRate(Const.PLAYER_MODE_SD);
                ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
                setModeListChecked(videoInfo.getRate());
                setBiteText();
                normalPlay(mModeSparse.get(Const.PLAYER_MODE_SD).getPlayUrl());
            } else if (rate != Const.PLAYER_MODE_AUTO && mModeSparse.indexOfKey(Const.PLAYER_MODE_AUTO) >= 0) {
                videoInfo.setRate(Const.PLAYER_MODE_AUTO);
                ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
                setModeListChecked(videoInfo.getRate());
                setBiteText();
                normalPlay(mModeSparse.get(Const.PLAYER_MODE_AUTO).getPlayUrl());
            } else if (rate != Const.PLAYER_MODE_TS && mModeSparse.indexOfKey(Const.PLAYER_MODE_TS) >= 0) {
                videoInfo.setRate(Const.PLAYER_MODE_TS);
                ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
                setModeListChecked(videoInfo.getRate());
                setBiteText();
                p2pPlay(mModeSparse.get(Const.PLAYER_MODE_TS).getPlayUrl());
            }
        } else {
            if (mModeSparse.indexOfKey(rate) >= 0) {
                normalPlay(mModeSparse.get(rate).getPlayUrl());
            } else if (rate != Const.PLAYER_MODE_SD && mModeSparse.indexOfKey(Const.PLAYER_MODE_SD) >= 0) {
                videoInfo.setRate(Const.PLAYER_MODE_SD);
                ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
                setModeListChecked(videoInfo.getRate());
                setBiteText();
                normalPlay(mModeSparse.get(Const.PLAYER_MODE_SD).getPlayUrl());
            } else if (rate != Const.PLAYER_MODE_HD && mModeSparse.indexOfKey(Const.PLAYER_MODE_HD) >= 0) {
                videoInfo.setRate(Const.PLAYER_MODE_HD);
                ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
                setModeListChecked(videoInfo.getRate());
                setBiteText();
                normalPlay(mModeSparse.get(Const.PLAYER_MODE_HD).getPlayUrl());
            } else {//点播最后转为最低码率播放
                videoInfo.setRate(mModeSparse.keyAt(mModeSparse.size() - 1));
                ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
                setModeListChecked(videoInfo.getRate());
                setBiteText();
                normalPlay(mModeSparse.valueAt(mModeSparse.size() - 1).getPlayUrl());
            }
        }
    }

    /**
     * 正常播放,高清或者标清
     *
     * @param path
     */
    private void normalPlay(String path) {
//		Log.i(TAG, "播放时候时移当前时间："+currentPlayTime+"+++++++");
        if (!Utils.isNetConneted(mContext) && isLiveFlag) { //点播分为在线播放 和 下载后缓存播放
            LogUtil.i(TAG, "MediaPlayFragment normalPlay() net is disconnected....");
            playError(Const.ERROR_NET_EXCEPTION, R.string.error_net_exception);
            return;
        }

        if (TextUtils.isEmpty(path)) {
            LogUtil.i(TAG, "MediaPlayFragment normalPlay() path is null....");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_path_null);
            return;
        }
        finalVideoUrl = path;
        LogUtil.i(TAG, "MediaPlayFragment normalPlay() isSufaceCreated = " + isSufaceCreated + ",finalVideoUrl = " + finalVideoUrl);
        currentRate = videoInfo.getRate();
        if (isSufaceCreated) {
            mVideoView.setVideoPath(finalVideoUrl);
            if (!isLiveFlag && currentPosition != 0) {
                mVideoView.seekTo(currentPosition);
            }
        }
    }

    /**
     * p2p直播，即 极速播放
     *
     * @param playId
     */
    private void p2pPlay(String playId) {
        mP2pPlugin = CBoxP2P.getInstance(mContext);
        mP2pPlugin.play(playId);
        mP2pPlugin.setOnP2PBufferListener(new OnP2PBufferListener() {

            @Override
            public void p2pBufferSuccess(String p2pUrl) {
                // TODO Auto-generated method stub
                LogUtil.i(TAG, "p2pBufferSuccess start play fast....");

                //for time calc start
                p2pBufferTime = System.currentTimeMillis();
                LogUtil.i(TAG, "p2pBuffer Time = " + (p2pBufferTime - startPlayTime));
                //for time calc end

                normalPlay(p2pUrl);
            }

            @Override
            public void p2pBufferFailed(int errNum, String errInfo) {
                LogUtil.i(TAG, "p2pBufferFailed start play slow.... errInfo = " + errInfo + ",errNum = " + errNum);
                if (errNum == 504) {//因版权原因, 本时段节目暂停播放！
                    LogUtil.i(TAG, "MediaPlayFragment p2pBufferFailed() live video copyright is limit errNum  504");
                    playError(Const.ERROR_INVALID_COPYRIGHT, R.string.error_invalid_copyright);
                }/*else if(mModeSparse != null && mModeSparse.size() == 1){//p2p播放异常，但只有p2p播放模式(极速)
					LogUtil.i(TAG, "MediaPlayFragment p2pBufferFailed() but only p2p play...");
					playError(errNum, errInfo);
				}*/ else if (mP2pBufferCount < RETRY_P2P_BUFFER_COUNT) {
                    LogUtil.i(TAG, "MediaPlayFragment p2pBufferFailed() p2p play again ....");
                    mP2pBufferCount++;
                    play(videoInfo.getRate());
                } else {
                    convertPlay(Const.PLAYER_MODE_TS);
                }

            }
        });
    }

    /**
     * 播放错误，自动转换播放
     *
     * @param nowExceptionRate 当前异常码率
     */
    private void convertPlay(int nowExceptionRate) {
//		ToastUtil.showToast(mContext, "正在转为标清播放... ", Toast.LENGTH_SHORT);


        if (isLiveFlag && isFullScreen && mSeekBarTimeShift != null) {
            mSeekBarTimeShift.setEnabled(true);
        }

        if (mModeSparse == null) {
            LogUtil.i(TAG, "MediaPlayFragment convertPlay() mModeSparse == null ....");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_exception);
            return;
        }

        if (mModeSparse.get(nowExceptionRate) != null) {
            mModeSparse.get(nowExceptionRate).setPlayException(true);
        }

        if (mModeSparse.size() <= 1) {
            LogUtil.i(TAG, "MediaPlayFragment convertPlay() mModeSparse.size() <= 1 ....");//只有一个码率，无法切换码率播放
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_exception);
            return;
        }

        if (isRateAvailable(nowExceptionRate, Const.PLAYER_MODE_SD)) {
            videoInfo.setRate(Const.PLAYER_MODE_SD);
        } else if (isRateAvailable(nowExceptionRate, Const.PLAYER_MODE_HD)) {
            videoInfo.setRate(Const.PLAYER_MODE_HD);
        } else if (isRateAvailable(nowExceptionRate, Const.PLAYER_MODE_AUTO)) {
            videoInfo.setRate(Const.PLAYER_MODE_AUTO);
        } else if (isRateAvailable(nowExceptionRate, Const.PLAYER_MODE_TS)) {
            videoInfo.setRate(Const.PLAYER_MODE_TS);
        } else {
            LogUtil.i(TAG, "MediaPlayFragment convertPlay() covert failed...");
            playError(Const.ERROR_PLAY_EXCEPTION, R.string.error_exception);
            return;
        }
        ToastUtil.showToast(mContext, getString(R.string.switch_play_mode, getBiteText()), Toast.LENGTH_SHORT);
        setModeListChecked(videoInfo.getRate());
        setBiteText();
        play(videoInfo.getRate());
    }

    /**
     * 判断待转换的码率是否可用
     *
     * @param nowExceptionRate 当前异常码率
     * @param convertRate      将要转换的码率
     * @return
     */
    private boolean isRateAvailable(int nowExceptionRate, int convertRate) {
        return nowExceptionRate != convertRate
                && mModeSparse.indexOfKey(convertRate) >= 0
                && !mModeSparse.get(convertRate).isPlayException();
    }

    /**
     * 释放播放器
     *
     * @param playStart 释放播放器后再次播放时是否从头播放
     *                  默认关闭当前频道p2p缓冲
     */
    private void stopPlayer(boolean playStart) {
        stopPlayer(playStart, true);
    }

    /**
     * 释放播放器
     *
     * @param playStart   释放播放器后再次播放时是否从头播放
     * @param stopChannel 是否关闭当前频道p2p缓冲
     */
    private void stopPlayer(boolean playStart, boolean stopChannel) {
        isPlaySuccess = false;
        if (mVideoView != null) {
            currentPosition = playStart ? 0 : mVideoView.getCurrentPosition();
            mVideoView.pause();
            mVideoView.stopPlayback();
        }

        //频道之间互相切换的时候会出现p2p缓冲异常，初步判定可能是stopChannel()未执行完全，便开始新的频道缓冲导致的异常
        if (stopChannel && mP2pPlugin != null) {
            mP2pPlugin.stopChannel();
        }
		/*if(stopChannel){
			ThreadPool.getInstance().execute(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(mP2pPlugin != null){
						mP2pPlugin.stopChannel();
					}
				}
			});
		}*/
    }

    /***********************************end 播放器播放相关方法 end******************************************************************************/

    /************************************************start 码率相关方法 start************************************************************/

    /**
     * 获取码率显示文字
     */
    private String getBiteText() {
        String modeText = getString(R.string.player_mode_sd);
        if (getActivity() == null) {
            return modeText;
        }
        switch (videoInfo.getRate()) {
            case Const.PLAYER_MODE_TS:
                modeText = getString(R.string.player_mode_ts);
                break;
            case Const.PLAYER_MODE_SD:
                modeText = getString(R.string.player_mode_sd);
                break;
            case Const.PLAYER_MODE_HD:
                modeText = getString(R.string.player_mode_hd);
                break;
            case Const.PLAYER_MODE_PD:
                modeText = getString(R.string.player_mode_pd);
                break;
            case Const.PLAYER_MODE_UHD:
                modeText = getString(R.string.player_mode_uhd);
                break;
            case Const.PLAYER_MODE_AUTO:
                modeText = getString(R.string.player_mode_auto);
                break;
            default:
                break;
        }
        return modeText;
    }

    /**
     * 设置码率显示文字
     */
    private void setBiteText() {
        if (mTvBite != null) {
            mTvBite.setText(getBiteText());
        }
    }

    /**
     * 设置缓存播放时的码率
     *
     * @param videoInfo
     */
    private void setVodPlayModeList(VideoInfo videoInfo) {
        if (getActivity() == null) {
            return;
        }
        if (mModeList == null) {
            mModeList = new ArrayList<PlayMode>();
        } else {
            mModeList.clear();
        }
        if (mModeSparse == null) {
            mModeSparse = new SparseArray<PlayMode>();
        } else {
            mModeSparse.clear();
        }

        int rate = videoInfo.getRate();

        PlayMode mode = new PlayMode();
        mode.setTitle(getBiteText());
        mode.setPlayUrl(videoInfo.getDetailUrl());
        mode.setRate(rate);
        mode.setChecked(rate == videoInfo.getRate());
        mModeList.add(mode);
        mModeSparse.put(rate, mode);
    }

    /**
     * 获取视频源的高宽(h/w)比例
     *
     * @param resolution RESOLUTION=240x180
     * @return
     */
    private float getResolution(String resolution) {
        float ratio = 3 / 4f;
        if (TextUtils.isEmpty(resolution)) {
            return ratio;
        }
        String[] split = resolution.split("=");//["RESOLUTION","240x180"]
        if (split == null || split.length < 2) {
            return ratio;
        }

        String[] wh = split[1].split("x");//["240","180"]
        int w = Utils.strToInt(wh[0]);
        int h = Utils.strToInt(wh[1]);

        if (w == 0 || h == 0) {
            return ratio;
        }

        return h / (float) w;

    }


    /**
     * 设置点播码率相关信息
     *
     * @param hlsUrl  源地址
     * @param hlsInfo 源地址访问网络后获取到的码率源信息
     */
    private void setVodPlayModeList(String hlsUrl, String hlsInfo) {
        if (getActivity() == null) {
            return;
        }
        if (mModeList == null) {
            mModeList = new ArrayList<PlayMode>();
        } else {
            mModeList.clear();
        }
        if (mModeSparse == null) {
            mModeSparse = new SparseArray<PlayMode>();
        } else {
            mModeSparse.clear();
        }

        ByteArrayInputStream bais = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            bais = new ByteArrayInputStream(hlsInfo.getBytes());
            isr = new InputStreamReader(bais);
            br = new BufferedReader(isr);
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                if (line.contains("BANDWIDTH")) {
                    String[] rateInfos = line.split(",");
                    String bandWidth = rateInfos[1].trim();//BANDWIDTH=204800
                    int width = Utils.strToInt(bandWidth.split("=")[1]);
                    if (width / 1000 > 1600) {
                        if (mModeSparse.indexOfKey(Const.PLAYER_MODE_PD) >= 0) { //超高清模式可能有很多，只要一个
                            continue;
                        }
                        //添加超高清模式
                        PlayMode modeUhd = new PlayMode();
                        modeUhd.setTitle(getString(R.string.player_mode_uhd));
                        modeUhd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeUhd.setRate(Const.PLAYER_MODE_UHD);
                        modeUhd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_UHD);
                        mModeList.add(modeUhd);
                        mModeSparse.put(Const.PLAYER_MODE_UHD, modeUhd);

                    } else if (width / 1000 > 900 && width / 1000 <= 1600) {

                        //添加超清模式
                        PlayMode modePd = new PlayMode();
                        modePd.setTitle(getString(R.string.player_mode_pd));
                        modePd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modePd.setRate(Const.PLAYER_MODE_PD);
                        modePd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_PD);
                        mModeList.add(modePd);
                        mModeSparse.put(Const.PLAYER_MODE_PD, modePd);
                    } else if (width / 1000 > 600 && width / 1000 <= 900) {
                        //添加高清模式
                        PlayMode modeHd = new PlayMode();
                        modeHd.setTitle(getString(R.string.player_mode_hd));
                        modeHd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeHd.setRate(Const.PLAYER_MODE_HD);
                        modeHd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_HD);
                        mModeList.add(modeHd);
                        mModeSparse.put(Const.PLAYER_MODE_HD, modeHd);
                    } else if (width / 1000 > 300 && width / 1000 <= 600) {
                        //添加标清模式
                        PlayMode modeSd = new PlayMode();
                        modeSd.setTitle(getString(R.string.player_mode_sd));
                        modeSd.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeSd.setRate(Const.PLAYER_MODE_SD);
                        modeSd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_SD);
                        mModeList.add(modeSd);
                        mModeSparse.put(Const.PLAYER_MODE_SD, modeSd);
                    } else if (width / 1000 <= 300) {

                        float resolution = 0;
                        if (rateInfos.length >= 3) {
                            resolution = getResolution(line.split(",")[2]);//line.split(",")[2] == RESOLUTION=240x180
                        }
                        if (resolution == 2 / 3f) {//极速码率比例为3:2时，解码失败，暂时隐藏
                            continue;
                        }
                        //添加极速模式
                        PlayMode modeTs = new PlayMode();
                        modeTs.setTitle(getString(R.string.player_mode_ts));
                        modeTs.setPlayUrl(StringUtil.fitVodModeUrl(hlsUrl, br.readLine()));
                        modeTs.setRate(Const.PLAYER_MODE_TS);
                        modeTs.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_TS);
                        mModeList.add(modeTs);
                        mModeSparse.put(Const.PLAYER_MODE_TS, modeTs);
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtil.i("zl", "MediaPlayFragment setVodPlayModeList() e = " + e.getMessage());
        } finally {
            try {
                if (br != null) {
                    br.close();
                    br = null;
                }
                if (isr != null) {
                    isr.close();
                    isr = null;
                }
                if (bais != null) {
                    bais.close();
                    bais = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        sortModeList(mModeList);

    }


    /**
     * 将码率列表按码率值降序排列，根据Const中的码率设定，码率值越大，视频越清晰
     *
     * @param modes
     */
    private void sortModeList(List<PlayMode> modes) {
        if (modes != null && modes.size() > 0) {
            Collections.sort(modes, new Comparator<PlayMode>() {

                @Override
                public int compare(PlayMode lhs, PlayMode rhs) {

                    // TODO Auto-generated method stub
                    if (lhs.getRate() > rhs.getRate()) {
                        return -1;
                    } else if (lhs.getRate() < rhs.getRate()) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
    }


    /**
     * 设置直播码率相关信息
     *
     * @param hdUrl 高清播放地址
     * @param sdUrl 标清播放地址
     */
    private void setLivePlayModeList(String hdUrl, String sdUrl) {
        if (getActivity() == null) {
            return;
        }
        if (mModeList == null) {
            mModeList = new ArrayList<PlayMode>();
        } else {
            mModeList.clear();
        }

        if (mModeSparse == null) {
            mModeSparse = new SparseArray<PlayMode>();
        } else {
            mModeSparse.clear();
        }

        //添加高清模式
        if (!TextUtils.isEmpty(hdUrl)) {
            PlayMode modeHd = new PlayMode();
            modeHd.setTitle(getString(R.string.player_mode_hd));
            modeHd.setPlayUrl(hdUrl);
            modeHd.setRate(Const.PLAYER_MODE_HD);
            modeHd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_HD);
            mModeList.add(modeHd);
            mModeSparse.put(Const.PLAYER_MODE_HD, modeHd);
        }
        //添加标清模式
        if (!TextUtils.isEmpty(sdUrl)) {
            PlayMode modeSd = new PlayMode();
            modeSd.setTitle(getString(R.string.player_mode_sd));
            modeSd.setPlayUrl(sdUrl);
            modeSd.setRate(Const.PLAYER_MODE_SD);
            modeSd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_SD);
            mModeList.add(modeSd);
            mModeSparse.put(Const.PLAYER_MODE_SD, modeSd);
        }
    }

    /**
     * 通过Vdn列表信息设置直播码率相关信息
     *
     * @param liveInfo
     */
    private void setLivePlayModeList(VdnLiveInfo liveInfo) {
        if (getActivity() == null) {
            return;
        }
        if (mModeList == null) {
            mModeList = new ArrayList<PlayMode>();
        } else {
            mModeList.clear();
        }
        mModeAdapter = null;//如果重新获取过码率列表，清空码率适配器

        if (mModeSparse == null) {
            mModeSparse = new SparseArray<PlayMode>();
        } else {
            mModeSparse.clear();
        }

		/*添加标清模式(支持时移) 已舍弃.....
		PlayMode modeSd = new PlayMode();
		modeSd.setTitle(getString(R.string.player_mode_sd));
		modeSd.setPlayUrl(liveInfo.getHls_url().getHls3());
		modeSd.setRate(Const.PLAYER_MODE_SD);
		modeSd.setChecked(videoInfo.getRate()==Const.PLAYER_MODE_SD);
		mModeList.add(modeSd);
		mModeSparse.put(Const.PLAYER_MODE_SD, modeSd);*/

        if (PlayerConfig.isP2pSupport) {
            //添加极速模式(P2P模式播放,不支持时移)
            PlayMode modeTs = new PlayMode();
            modeTs.setTitle(getString(R.string.player_mode_ts));
            modeTs.setPlayUrl(p2pPlayId);
            modeTs.setRate(Const.PLAYER_MODE_TS);
            modeTs.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_TS);
            mModeList.add(modeTs);
            mModeSparse.put(Const.PLAYER_MODE_TS, modeTs);
        }

        if (liveInfo == null || liveInfo.getHls_url() == null) {
            LogUtil.i(TAG, "MediaPlayFragment setLivePlayModeList() VdnLiveInfo is null...");
            return;
        }

        //添加高清模式(支持时移)
        if (isLivePolicyOpen(channelId, Const.PLAYER_MODE_SD)
                && !TextUtils.isEmpty(liveInfo.getHls_url().getHls2())) {
            PlayMode modeSd = new PlayMode();
            modeSd.setTitle(getString(R.string.player_mode_sd)); //要求显示成标清了，
            modeSd.setPlayUrl(liveInfo.getHls_url().getHls2());
            modeSd.setRate(Const.PLAYER_MODE_SD);
            modeSd.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_SD);
            mModeList.add(modeSd);
            mModeSparse.put(Const.PLAYER_MODE_SD, modeSd);
        }
        //添加自适应模式(支持时移)
        if (isLivePolicyOpen(channelId, Const.PLAYER_MODE_AUTO)
                && !TextUtils.isEmpty(liveInfo.getHls_url().getHls1())) {
            PlayMode modeAuto = new PlayMode();
            modeAuto.setTitle(getString(R.string.player_mode_auto));
            modeAuto.setPlayUrl(liveInfo.getHls_url().getHls1());
            modeAuto.setRate(Const.PLAYER_MODE_AUTO);
            modeAuto.setChecked(videoInfo.getRate() == Const.PLAYER_MODE_AUTO);
            mModeList.add(modeAuto);
            mModeSparse.put(Const.PLAYER_MODE_AUTO, modeAuto);
        }

        sortModeList(mModeList);
    }

    /**
     * 直播策略是否打开，无限制
     *
     * @param channelId
     * @return
     */
    private boolean isLivePolicyOpen(String channelId, int rate) {
        if (mLivePolicy == null || mLivePolicy.get(channelId) == null) {
            return true;
        } else if (rate == Const.PLAYER_MODE_AUTO) {
            return Utils.strToInt(mLivePolicy.get(channelId).getDb()) == Const.OPEN;
        } else if (rate == Const.PLAYER_MODE_SD) {
            return Utils.strToInt(mLivePolicy.get(channelId).getSd()) == Const.OPEN;
        } else {
            return true;
        }
    }


    /**
     * 设置当前码率
     *
     * @param currentRate
     */
    private void setModeListChecked(int currentRate) {
        for (PlayMode mode : mModeList) {
            if (mode.getRate() == currentRate) {
                mode.setChecked(true);
            } else {
                mode.setChecked(false);
            }
        }
        if (isFullScreen) {
            setModeAdapter();
        }
    }

    /**
     * 设置码率适配器
     */
    private void setModeAdapter() {
        if (mLvPlayMode == null) {
            return;
        }
        if (mModeAdapter == null) {
            mModeAdapter = new PlayModeAdaper(mContext, mModeList, R.layout.player_mode_item_view);
            mLvPlayMode.setAdapter(mModeAdapter);
        } else {
            mModeAdapter.setData(mModeList);
            mModeAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 弹出码率选择窗口
     */
    private void popupModeView() {
        if (mLlPlayMode.isShown()) {
            AnimController.getInstance().scaleOut(mLlPlayMode, 200, 0);
            setSelected(mTvBite, false);
            return;
        }

        if (mModeList == null || mModeList.size() == 0) {
            return;
        }

        setModeAdapter();

        int[] location = new int[2];
        mTvBite.getLocationOnScreen(location);
        RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mLlPlayMode.getLayoutParams();

        linearParams.width = mTvBite.getWidth() + 20;//将码率列表宽度加20
        linearParams.rightMargin = Utils.screenWidth(mContext) - location[0] - mTvBite.getWidth() - 10;
        linearParams.bottomMargin = mLlBottom.getHeight() + 10;
//		linearParams.rightMargin = mTvBite.getRight();
//		linearParams.bottomMargin = mTvBite.getBottom() + mTvBite.getHeight();
        mLlPlayMode.setLayoutParams(linearParams);

        mLlPlayMode.setVisibility(View.VISIBLE);
        AnimController.getInstance().scaleIn(mLlPlayMode, 200, 0);

        setSelected(mTvBite, true);

        //响应popupwindonw中listview点击事件需设置mWindow.setFocusable(true);
        //见mediacontroller, 已修改成addview形式添加controller,不存在listview不可点击的情况
        mLvPlayMode.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub

//					mLlPlayMode.setVisibility(View.GONE);
                AnimController.getInstance().scaleOut(mLlPlayMode, 200, 0);
                setSelected(mTvBite, false);

                PlayMode playMode = mModeList.get(position);
                if (playMode.isChecked()) {
                    return;
                }

                if (mMediaController != null) {
                    mMediaController.clear();
                }
                stopPlayer(false);
                videoInfo.setRate(playMode.getRate());//当前码率更新
                llLoading.setVisibility(View.VISIBLE);//显示正在加载
                mTvBite.setText(playMode.getTitle());//码率显示文字更新
                setModeListChecked(playMode.getRate());//设置码率已选择

                if (isLiveFlag && isTimeShifting) {
                    ToastUtil.showToast(mContext, R.string.timeshift_renew_live, Toast.LENGTH_SHORT);
                    isTimeShifting = false;
                    createTimeShiftEPG(currentType);
                }
                if (isLiveFlag) {
                    mSeekBarTimeShift.setEnabled(videoInfo.getRate() != Const.PLAYER_MODE_TS);
                }
                play(playMode.getRate());

            }
        });
    }

    /**
     * 显示音量控制视图
     */
    private void popupVolumeView() {
        if (mLlVerticalVolume.isShown()) {
            AnimController.getInstance().scaleOut(mLlVerticalVolume, 200, 0);
            return;
        }

        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mVsbVolume.setProgress(mCurrentVolume);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mLlVerticalVolume.getLayoutParams();
        layoutParams.bottomMargin = mLlBottom.getHeight() + 10;
		/*if(isPortraitScreen()){
			layoutParams.height = mContext.getResources().getDimensionPixelOffset(R.dimen.volume_height_item);
		}else{
			layoutParams.height = mContext.getResources().getDimensionPixelOffset(R.dimen.volume_height);
		}*/
        mLlVerticalVolume.setLayoutParams(layoutParams);

        mLlVerticalVolume.setVisibility(View.VISIBLE);
        AnimController.getInstance().scaleIn(mLlVerticalVolume, 200, 0);

    }

    /**
     * 设置系统音量
     *
     * @param index
     */
    public void setVolume(int index) {
        if (mAudioManager != null) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, AudioManager.FLAG_SHOW_UI);
            if (mVsbVolume != null) {
                mVsbVolume.setProgress(index);
            }
            mCurrentVolume = index;
        }
    }

    public void onKeyDownVolume(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (mCurrentVolume >= 1) {
                mCurrentVolume--;
            }
            setVolume(mCurrentVolume);

        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (mCurrentVolume < mMaxVolume) {
                mCurrentVolume++;
            }
            setVolume(mCurrentVolume);

        }
    }


    /************************************************end 码率相关方法 end************************************************************/
    /************************************************start 横竖屏切换相关方法 start************************************************************/
    /**
     * 是否竖屏
     *
     * @return
     */
    public boolean isPortraitScreen() {
        if (getActivity() == null) {
            return true;
        }
        int mCurrentOrientation = getResources().getConfiguration().orientation;
        return mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT;
    }

    /**
     * 全屏状态下 点击返回键设置竖屏(强制竖屏)
     */
    public void setPortrait() {
        // TODO Auto-generated method stub
        setActivityOriention(PORT);
        isAutoLandToPort = false;
		/*mClickToPort = true;
		mOrientationListener.disable();
		mHandler.removeMessages(SCREEN_STATE_CHANGE);
		mHandler.sendEmptyMessageDelayed(SCREEN_STATE_CHANGE, mScreenChangeTime);*/
    }

    /**
     * 半屏状态下 点击全屏键时设置横屏(强制横屏)
     */
    public void setLandscape() {
        // TODO Auto-generated method stub
        setActivityOriention(LAND);
        isAutoPortToLand = false;
		/*mClickToLand = true;
		mOrientationListener.disable();
		mHandler.removeMessages(SCREEN_STATE_CHANGE);
		mHandler.sendEmptyMessageDelayed(SCREEN_STATE_CHANGE, mScreenChangeTime);*/
    }

    /**
     * 设置横屏或者竖屏
     *
     * @param oriention ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
     *                  ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
     *                  ...
     */
    public void setActivityOriention(int oriention) {
        currentScreen = oriention;
        isFullScreen = (oriention == LAND);
        if (mActivity.getRequestedOrientation() != oriention) {
            mActivity.setRequestedOrientation(oriention);
        }
    }

    /**
     * 得到屏幕旋转的状态
     *
     * @return 1代表可旋转 0代表不可旋转
     */
    private int getRotationStatus() {
        int status = 0;
        try {
            status = Settings.System.getInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION);
        } catch (SettingNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 观察屏幕旋转设置变化，类似于注册动态广播监听变化机制
     *
     * @author zengliang
     */
    class RotationObserver extends ContentObserver {
        ContentResolver mResolver;

        public RotationObserver(Handler handler) {
            super(handler);
            mResolver = mContext.getContentResolver();
            // TODO Auto-generated constructor stub
        }

        // 屏幕旋转设置改变时调用
        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            super.onChange(selfChange);
            //LogUtil.i(TAG, "getRotationStatus = " + getRotationStatus());
            if (getRotationStatus() == 1 && videoInfo.isPort() && videoInfo.isAutoScreen()) {
                mOrientationListener.enable();
            } else {
                mOrientationListener.disable();
            }
        }

        public void startObserver() {
            mResolver.registerContentObserver(Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), false, this);
        }

        public void stopObserver() {
            mResolver.unregisterContentObserver(this);
        }
    }

    /************************************************end 横竖屏切换相关方法 end************************************************************/

    /************************************************start 广告展示相关方法 start************************************************************/
    /**
     * 操作暂停图片广告
     */
    private void handlePauseAd() {
        if (isPlaySuccess) {
            if (mVideoView.isPlaying()) {
//				mVideoView.setAdPlaying(false);
                mMediaController.setAdPlaying(false);
                if (adFrag != null && adFrag.isAdded()) {
                    adFrag.dettachSelf();
                }
            } else {
                if (isAdPausePhotoError) {//暂停图片广告异常，就不在创建AdFragment
                    adFrag = null;
                    return;
                }
//				mMediaController.hide(); //广告显示成功时再隐藏
                if (adFrag != null && adFrag.isDetached()) {
                    adFrag.attachSelf();
                } else {
                    showAd(Const.AD_PAUSE);
                }
            }
        }
    }

    /**
     * 是否包含后贴片广告
     *
     * @return
     */
    private boolean hasAfterAd() {
        if (videoInfo.getAdInfo() == null) {
            return false;
        }
        return !Const.AD_MODE_OVER.equals(videoInfo.getAdInfo().getAdMode());
    }

    /**
     * 判断是否所有视频都播放广告
     *
     * @return
     */
    private boolean isAdOver() {
        if (videoInfo.getAdInfo() == null) {
            return false;
        }
        return Const.AD_MODE_OVER.equals(videoInfo.getAdInfo().getAdMode());
    }


/*	private void removeAd(){
		FragmentTransaction ft = getChildFragmentManager().beginTransaction();
		adFrag = AdFragment.newInstance(adInfo);
		ft.add(R.id.ll_ad_area, adFrag,AD_TAG);
		ft.commit();
	}*/

    /**
     * 显示广告
     *
     * @param category 广告类型
     *                 Const.ADD_CALL  or Const.ADD_PAUSE  or  Const.AFTER;
     */
    private void showAd(int category) {
        AdInfo adInfo = videoInfo.getAdInfo();
        if (adInfo == null) {
            isAdPausePhotoError = true;
            return;
        }
        if (isLiveFlag) {
            adInfo.setChannel(isAdOver() ? p2pPlayId : channelId);

            adInfo.setFlag(videoInfo.getFlag());
            adInfo.setCategory(category);
            adInfo.setRandom(Utils.generateRandom() + "");
        } else {
            adInfo.setFlag(videoInfo.getFlag());
            adInfo.setCategory(category);
            adInfo.setRandom(Utils.generateRandom() + "");
        }

        llAdArea.setVisibility(View.VISIBLE);
        if (category != Const.AD_PAUSE) {
//			mVideoView.setAdPlaying(true);
            mMediaController.setAdPlaying(true);
        } else {
            isVideoPasued = true;
            mCurrentAdCategory = category;
        }


        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        adFrag = AdFragment.newInstance(adInfo);
        if (!adFrag.isAdded())
            ft.add(R.id.ll_ad_area, adFrag, AD_TAG);
        ft.commit();

        adFrag.setOnAdListener(new AdFragment.OnAdListener() {

            @Override
            public void onAdStartPlay(int adCategory) {
                // TODO Auto-generated method stub
                llLoading.setVisibility(View.GONE);
                llAdArea.setVisibility(View.VISIBLE);
                mCurrentAdCategory = adCategory;

//				mVideoView.setAdPlaying(true);
                mMediaController.setAdPlaying(true);
            }

            @Override
            public void onAdSectionCompletion() {
                // TODO Auto-generated method stub
                llLoading.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAdCompletion() {
                // TODO Auto-generated method stub
                LogUtil.i(TAG, " adFrag setOnAdCompletonListener");
                LogUtil.i(TAG, "adFrag playSuccess = " + isPlaySuccess);

//				isAdPlaying = false;
                if (!mMediaController.isAdPlaying()) {
                    return;
                }
                mCurrentAdCategory = 0;
                llAdArea.setVisibility(View.GONE);
                mVideoView.setVisibility(View.VISIBLE);
//				mVideoView.setAdPlaying(false);
                mMediaController.setAdPlaying(false);
                if (isPlaySuccess) {
                    if (isAdPausePhotoError) {
                        return;
                    }
                    llLoading.setVisibility(View.GONE);
                    mVideoView.start();
                    isVideoPasued = false;
                    if (isLiveFlag && isFullScreen && videoInfo.isTimeShift()) {
                        initTimeShift();
                    }
                    mMediaController.show();
                } else {
                    llLoading.setVisibility(View.VISIBLE);
                    if (isPlayComplete) {
                        stopPlayer(true);
//						play(videoInfo.getRate());
                        if (mOnPlayerListener != null) {
                            mOnPlayerListener.onPlayComplete();
                        }
                    }
                }
            }

            @Override
            public void onAdPhotoClose() {
                // TODO Auto-generated method stub
//				mVideoView.setAdPlaying(false);
                mCurrentAdCategory = 0;
                mMediaController.setAdPlaying(false);
                mMediaController.show();
            }

            @Override
            public void onAdPhotoLoadSuccess(Bitmap bitmap) {
                // TODO Auto-generated method stub
                if (mMediaController != null) {
                    mMediaController.hide();
                }
            }

            @Override
            public void onAdError(int adCategory, String strMsg) {
                // TODO Auto-generated method stub
//				ToastUtil.showToast(mContext, "AdFragment:msg = " + strMsg + ",广告自动销毁...", Toast.LENGTH_SHORT);
                isAdPausePhotoError = (adCategory == Const.AD_PAUSE);
                mCurrentAdCategory = 0;
				/*isAdError = true;
				if(!isAdPausePhotoError && finalVideoUrl != null){
					normalPlay(finalVideoUrl);
				}*/
            }
        });
    }

    /************************************************end 广告展示相关方法 end************************************************************/
    /************************************************start 右上方信息列表相关方法 start****************************************************/
    /**
     * 添加右侧列表fragment，供Activity调用
     *
     * @param tab
     * @param fragment
     */
    public void addRightInfo(int tab, Fragment fragment) {
        if (fragment == null) {
            return;
        }
        if (mRightFrags == null) {
            mRightFrags = new SparseArray<Fragment>();
        }
        if (mRightFrags.indexOfKey(tab) >= 0) {
            mRightFrags.remove(tab);
        }
//		setListScrollListener(fragment);
        mRightFrags.put(tab, fragment);
        switch (tab) {
            case TAB_RECOM:
                if (mTvTopRecommend != null) {
                    mTvTopRecommend.setVisibility(View.VISIBLE);
                }
                break;
            case TAB_CHAN:
                if (mTvTopChannel != null) {
                    mTvTopChannel.setVisibility(View.VISIBLE);
                }
                break;
            case TAB_EPG:
                if (mTvTopEpg != null) {
                    mTvTopEpg.setVisibility(View.VISIBLE);
                }
                break;
            case TAB_EPI:
                if (mTvTopEpiSelect != null) {
                    mTvTopEpiSelect.setVisibility(View.VISIBLE);
                }
                break;
            case TAB_BEST:
                if (mTvTopBestSelect != null) {
                    mTvTopBestSelect.setVisibility(View.VISIBLE);
                }
                break;

            default:
                break;
        }

    }

    /**
     * 根据设置 控制视图右上侧按钮的显示与隐藏
     */
    private void setTopRightButtonVisibility() {

        if (mRightFrags == null || mRightFrags.size() == 0) {
            return;
        }
        if (mRightFrags.indexOfKey(TAB_RECOM) >= 0 && mTvTopRecommend != null) {
            mTvTopRecommend.setVisibility(View.VISIBLE);
        } else if (mTvTopRecommend != null) {
            mTvTopRecommend.setVisibility(View.GONE);
        }

        if (mRightFrags.indexOfKey(TAB_CHAN) >= 0 && mTvTopChannel != null) {
            mTvTopChannel.setVisibility(View.VISIBLE);
        } else if (mTvTopChannel != null) {
            mTvTopChannel.setVisibility(View.GONE);
        }

        if (mRightFrags.indexOfKey(TAB_EPG) >= 0 && mTvTopEpg != null) {
            mTvTopEpg.setVisibility(View.VISIBLE);
        } else if (mTvTopEpg != null) {
            mTvTopEpg.setVisibility(View.GONE);
        }

        if (mRightFrags.indexOfKey(TAB_EPI) >= 0 && mTvTopEpiSelect != null) {
            mTvTopEpiSelect.setVisibility(View.VISIBLE);
        } else if (mTvTopEpiSelect != null) {
            mTvTopEpiSelect.setVisibility(View.GONE);
        }

        if (mRightFrags.indexOfKey(TAB_BEST) >= 0 && mTvTopBestSelect != null) {
            mTvTopBestSelect.setVisibility(View.VISIBLE);
        } else if (mTvTopBestSelect != null) {
            mTvTopBestSelect.setVisibility(View.GONE);
        }
    }

    /**
     * 控制显示右侧列表信息
     *
     * @param nowTab
     */
    private void showTopRightInfo(final int nowTab) {
        if (currentTab == nowTab) {
            setTopRightTextSelected(TAB_NULL);
            AnimController.getInstance().slideRightOut(mLlRight, 350, 0);
            hidePreFrag();
            currentTab = TAB_NULL;
        } else {
            setTopRightTextSelected(nowTab);
            currentTab = nowTab;
//			mLlRight.setVisibility(View.GONE);
            AnimController.getInstance().slideRightIn(mLlRight, 350, 0, new AnimCallback() {

                @Override
                public void onAnimationStart() {
                    // TODO Auto-generated method stub
                    if (nowTab != currentTabData) {
                        detachPreFrag();
                    } else {
                        showNowFrag(nowTab);
                    }
                }

                @Override
                public void onAnimationEnd() {
                    // TODO Auto-generated method stub
                    addNextFrag(nowTab);
                }

            });
        }
    }

    /**
     * dettach掉之前显示在右侧的视图
     */
    private void detachPreFrag() {
        String currentTag = getTag(currentTabData);
        FragmentManager fragMgr = getChildFragmentManager();
        FragmentTransaction fragTran = fragMgr.beginTransaction();
        if (currentTag != null) {//移除当前的Frag
            fragTran.detach(fragMgr.findFragmentByTag(currentTag));
        }
        fragTran.commit();
    }

    /**
     * hide掉之前显示在右侧的视图
     */
    private void hidePreFrag() {
        String currentTag = getTag(currentTabData);
        FragmentManager fragMgr = getChildFragmentManager();
        FragmentTransaction fragTran = fragMgr.beginTransaction();
        if (currentTag != null) {//移除当前的Frag
            fragTran.hide(fragMgr.findFragmentByTag(currentTag));
        }
        fragTran.commit();
    }

    /**
     * show掉之前显示在右侧的视图
     */
    private void showNowFrag(int nowTab) {
        String currentTag = getTag(nowTab);
        FragmentManager fragMgr = getChildFragmentManager();
        FragmentTransaction fragTran = fragMgr.beginTransaction();
        if (currentTag != null) {//移除当前的Frag
            fragTran.show(fragMgr.findFragmentByTag(currentTag));
        }
        fragTran.commit();
    }

    /**
     * 添加当前点击的fragment到右侧视图
     *
     * @param nowTab
     */
    private void addNextFrag(int nowTab) {

        if (currentTabData == nowTab) {
            return;
        }
//		String currentTag = getTag(currentTabData);
        String nowTag = getTag(nowTab);

        FragmentManager fragMgr = getChildFragmentManager();
        FragmentTransaction fragTran = fragMgr.beginTransaction();
		/*if(currentTag != null){//移除当前的Frag
			fragTran.detach(fragMgr.findFragmentByTag(currentTag));
		}*/
        if (mRightFrags.get(nowTab).isDetached()) {
            fragTran.attach(mRightFrags.get(nowTab));
        } else {
            if (mRightFrags != null && mRightFrags.get(nowTab) != null && !mRightFrags.get(nowTab).isAdded())
                fragTran.add(R.id.ll_right, mRightFrags.get(nowTab), nowTag);
        }
        currentTabData = nowTab;
        fragTran.commit();
    }

    /**
     * 重新初始化右侧列表相关变量
     */
    private void initDefault() {
        currentPosition = 0;
        currentTab = TAB_NULL;
        mP2pBufferCount = 0;
        if (getActivity() == null) {
            return;
        }
        if (currentTabData != TAB_NULL) {
            String currentTag = getTag(currentTabData);
            FragmentManager fragMgr = getChildFragmentManager();
            FragmentTransaction fragTran = fragMgr.beginTransaction();
            if (currentTag != null) {
                fragTran.detach(fragMgr.findFragmentByTag(currentTag));
            }
            fragTran.commit();
            currentTabData = TAB_NULL;
        }
    }

    /**
     * 根据tab获取tag值
     *
     * @param tab
     * @return
     */
    private String getTag(int tab) {
        String tag = null;
        switch (tab) {
            case TAB_RECOM:
                tag = Const.TAG_RECO;
                break;
            case TAB_CHAN:
                tag = Const.TAG_CHAN;
                break;
            case TAB_EPG:
                tag = Const.TAG_EPG;
                break;
            case TAB_EPI:
                tag = Const.TAG_EPI;
                break;
            case TAB_BEST:
                tag = Const.TAG_BEST;
                break;
            case TAB_DET:
                tag = Const.TAG_DETA;
                break;
            default:
                break;
        }
        return tag;
    }


    private void setSelected(TextView view, boolean selected) {
        if (view != null) {
            view.setSelected(selected);
        }
    }

    /**
     * 设置右边按钮是否点击 更换背景和字体颜色
     *
     * @param nowTab 点击的tab
     */
    private void setTopRightTextSelected(int nowTab) {
        if (isLiveFlag) {
            switch (nowTab) {
                case TAB_NULL:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopChannel, false);
                    setSelected(mTvTopEpg, false);
                    break;
                case TAB_RECOM:
                    setSelected(mTvTopRecommend, true);
                    setSelected(mTvTopChannel, false);
                    setSelected(mTvTopEpg, false);
                    break;
                case TAB_CHAN:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopChannel, true);
                    setSelected(mTvTopEpg, false);
                    break;
                case TAB_EPG:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopChannel, false);
                    setSelected(mTvTopEpg, true);
                    break;
                default:
                    break;
            }
        } else {
            switch (nowTab) {
                case TAB_NULL:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopEpiSelect, false);
                    setSelected(mTvTopBestSelect, false);
                    setSelected(mTvTopVodDetail, false);
                    break;
                case TAB_RECOM:
                    setSelected(mTvTopRecommend, true);
                    setSelected(mTvTopEpiSelect, false);
                    setSelected(mTvTopBestSelect, false);
                    setSelected(mTvTopVodDetail, false);
                    break;
                case TAB_EPI:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopEpiSelect, true);
                    setSelected(mTvTopBestSelect, false);
                    setSelected(mTvTopVodDetail, false);
                    break;
                case TAB_BEST:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopEpiSelect, false);
                    setSelected(mTvTopBestSelect, true);
                    setSelected(mTvTopVodDetail, false);
                    break;
                case TAB_DET:
                    setSelected(mTvTopRecommend, false);
                    setSelected(mTvTopEpiSelect, false);
                    setSelected(mTvTopBestSelect, false);
                    setSelected(mTvTopVodDetail, true);
                    break;
                default:
                    break;
            }
        }
    }

    /************************************************end 右上方信息列表相关方法 end****************************************************/
    /************************************************
     * start 外部调用相关接口和相关方法 start
     ************************************************/
    public interface OnPlayerListener {
        /**
         * 播放缓冲完成
         */
        void onPlayStart();

        /**
         * 播放暂停改变
         *
         * @param isPaused
         */
        void onPlayPauseChanged(boolean isPaused);

        /**
         * 播放错误
         *
         * @param errorNo
         * @param errMsg
         */
        void onPlayError(int errorNo, String errMsg);

        /**
         * 播放完成
         */
        void onPlayComplete();
    }

    public interface OnShareListener {
        void onShare(VideoInfo videoInfo);
    }

    /**
     * 设置分享监听
     *
     * @param l
     */
    public void setOnShareListener(OnShareListener l) {
        this.mOnShareListener = l;
    }

    public interface OnCollectListener {
        void onCollect(VideoInfo videoInfo);
    }

    /**
     * 设置收藏监听
     *
     * @param l
     */
    public void setOnCollectListener(OnCollectListener l) {
        this.mOnCollectListener = l;
    }

    /**
     * 设置播放监听
     *
     * @param l
     */
    public void setOnPlayerListener(OnPlayerListener l) {
        this.mOnPlayerListener = l;
    }

    /**
     * 获取MediaController
     *
     * @return
     */
    public CustomerMediaController getMediaController() {
        return mMediaController;
    }

    /**
     * 获取收藏按钮视图
     *
     * @return
     */
    public TextView getCollectView() {
        return mTvCollect;
    }

    /**
     * 更新收藏视图
     */
    public void updateCollectView(boolean isCollected) {
        if (getActivity() == null) {
            return;
        }
        videoInfo.setHasCollected(isCollected);
        if (mTvCollect != null) {
            Drawable drawableFavOn = getResources().getDrawable(R.drawable.player_fav_on);
            Drawable drawableFavOff = getResources().getDrawable(R.drawable.player_fav_off);
            mTvCollect.setCompoundDrawablesWithIntrinsicBounds(null, isCollected ? drawableFavOn : drawableFavOff, null, null);
            mTvCollect.setText(isCollected ? R.string.player_fav_on : R.string.player_fav_off);
        }
    }

    /**
     * 判断MediaPlayer是否暂停
     *
     * @return
     */
    public boolean isVideoPaused() {
        return isVideoPasued;
    }

    /************************************************end 外部调用相关接口和相关方法 end**************************************************/

    /**
     * 监听来电
     */
    private void listeningPhoneState() {
        mPhoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_IDLE) {
                    if (mVideoView != null && !isPaused) {
                        mVideoView.start();
                    }
                } else {
                    if (mVideoView != null) {
                        mVideoView.pause();
                    }
                }
            }
        };
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    /**
     * 取消来电监听
     */
    private void cancelPhoneStateListen() {
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
    }

    /**
     * p2p设置初始化监听
     */
    private void setP2pInitListener() {
        pPlugin = CBoxP2P.getInstance(mContext);
        pPlugin.setOnP2PInitListener(new OnP2PInitListener() {

            @Override
            public void p2pInitUpdate(String msgInfo) {
                // TODO Auto-generated method stub
//				悦动不显示初始化过程
                if (videoInfo.isP2pProgress()) {
                    LogUtil.i(TAG, "displayInfo = " + msgInfo);
                    LogUtil.i(TAG, "Utils.filterNum(msgInfo) = " + Utils.filterNum(msgInfo));
                    int progress = Utils.filterNum(msgInfo);
                    mP2pInitProgress = progress > mP2pInitProgress ? progress : mP2pInitProgress;
                    if (msgInfo != null && !"".equals(msgInfo)) {
                        if (mDialog.isShowing()) {
                            mDialog.setMessage("p2p正在初始化中(" + mP2pInitProgress + "%)");
                        } else {
                            mDialog.show();
                            mDialog.setCancelable(false);
                        }
                    }
                }
            }

            @Override
            public void p2pInitSuccess() {
                // TODO Auto-generated method stub
                LogUtil.i(TAG, "p2pInitSuccess... ");
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.cancel();
                }
				/*if(mModeSparse != null && mModeSparse.size() > 0){
					play(videoInfo.getRate());
				}*/
            }

            @Override
            public void p2pInitFailed() {
                // TODO Auto-generated method stub
                LogUtil.i(TAG, "p2pInitFailed... ");
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.cancel();
                }
				/*if(mModeSparse != null && mModeSparse.size() > 0){
					convertPlay(Const.PLAYER_MODE_TS);
				}*/
            }
        });
    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
//		LogUtil.i(TAG,"MediaPlayFragment onStart");
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        LogUtil.i(TAG, "MediaPlayFragment onResume");
        isPaused = false;
        if (isSufaceCreated && !isVideoPasued && mVideoView != null) {
            mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
//		LogUtil.i(TAG,"MediaPlayFragment onPause");
        isPaused = true;
        if (mVideoView != null) {
            mVideoView.pause();
            currentPosition = mVideoView.getCurrentPosition();
        }
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
//		LogUtil.i(TAG,"MediaPlayFragment onStop");
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
//		LogUtil.i(TAG,"MediaPlayFragment onDestroyView");
        currentTab = TAB_NULL;
        currentTabData = TAB_NULL;

        isPlaySuccess = false;
        if (mP2pPlugin != null) {
            mP2pPlugin.stopBuffering();
        }

        //p2p直播必须重新缓冲进行播放，所以清空最终播放地址
        if (isLiveFlag && currentRate == Const.PLAYER_MODE_TS) {
            finalVideoUrl = null;
        }

        mHandler.removeMessages(UPDATE_FLOAT_TIME);
        mHandler.removeMessages(UPDATE_TIMESHIFT_SEEKBAR);
        mHandler.removeMessages(UPDATE_TIMESHIFT_SECONDARY_SEEKBAR);
        if (mMediaController != null) {
            mMediaController.hide();
        }
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
        if (mOrientationListener != null) {
            mOrientationListener.disable();
        }
        cancelPhoneStateListen();

        setViewsNull();
    }

    private void setViewsNull() {

        llLoading = null;
        mRlRootGesture = null;
        mLlVerticalVolume = null;
        llAdArea = null;

        btnFullScreen = null;
        mBtnExit = null;
        halfScreenControllerView = null;

        llTimeDisplay = null;
        seekbarHalf = null;

        mTvShare = null;
        mTvCollect = null;
        mLlLeft = null;

        mTvTopRecommend = null;
        mTvTopChannel = null;
        mTvTopEpg = null;
        mTvTopEpiSelect = null;
        mTvTopBestSelect = null;
        mTvTopVodDetail = null;

        mLvRight = null;
        mLlRight = null;

        mTvBite = null;
        mLvPlayMode = null;
        mLlPlayMode = null;

        mBtnVolume = null;
        mVsbVolume = null;
        mLlBottomRight = null;

        mTvFloatTime = null;
        mLlTimeShiftAdjust = null;
        mBtnTimeShiftAdd = null;
        mBtnTimeShiftCut = null;
        mLlTimeShift = null;
        mHsvTimeShift = null;
        mLlTimeShiftEpg = null;
        mLlTimeShiftRuler = null;
        mSeekBarTimeShift = null;
        mSeekBarFull = null;
        mLlBottom = null;

        liveControllerView = null;
        vodControllerView = null;
        fullScreenControllerView = null;

        rootView = null;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
//		LogUtil.i(TAG,"MediaPlayFragment onDestroy");

        mRotationObserver.stopObserver();

        stopPlayer(true);

        if (mLivePolicy != null) {
            mLivePolicy.clear();
            mLivePolicy = null;
        }
        if (mRightFrags != null) {
            mRightFrags.clear();
            mRightFrags = null;
        }
        if (mModeList != null) {
            mModeList.clear();
            mModeList = null;
        }
        if (mModeSparse != null) {
            mModeSparse.clear();
            mModeSparse = null;
        }

        mOrientationListener = null;
        mRotationObserver = null;
        mOnPreparedListener = null;
        mVideoView.setOnPreparedListener(null);
        mOnCompletionListener = null;
        mVideoView.setOnCompletionListener(null);
        mOnErrorListener = null;
        mVideoView.setOnErrorListener(null);
        mOnSurfaceListener = null;
        mVideoView.setOnSurfaceListener(null);


        mOnVideoPlayListener = null;
        mMediaController.setOnVideoPlayListener(null);
        mOnHiddenListener = null;
        mMediaController.setOnHiddenListener(null);
        mOnShownListener = null;
        mMediaController.setOnShownListener(null);
        mOnClickPauseListener = null;
        mMediaController.setOnClickPauseListener(null);
        mMediaController = null;
        mVideoView.setMediaController(null);

        mVideoView = null;
    }

    @Override
    public void onDetach() {
        // TODO Auto-generated method stub
        super.onDetach();
//		LogUtil.i(TAG,"MediaPlayFragment onDetach");
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
